/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "connection.h"
#include "dialog.h"
#include <QtNetwork>
#include <QTextEdit>
#include <QFileDialog>
//#include <qpushbutton>
//#include <QStringlist>
#include <QListWidget>
#include <QLineEdit>
#ifdef win32
#include "qt_windows.h"
#endif
#include "CRC/crc32.c.h"


class CriticalSection
{
    //CRITICAL_SECTION cs;
    QMutex m_mutex;
public:
//	CxQWinMsgHandlerCriticalSection()
//	{ InitializeCriticalSection(&cs); }
//	~CxQWinMsgHandlerCriticalSection()
//	{ DeleteCriticalSection(&cs); }

	void lock()
    {       m_mutex.lock();}
	void unlock()
    {       m_mutex.unlock();  }
};

static CriticalSection g_section;
static CriticalSection g_filesection;
static CriticalSection g_datafinishsection;
static CriticalSection g_datarunsection;
//CriticalSection g_dutyfinishsection;



//////////////////////////////////////////////////////////////////////////

void TEA_Decrypt(uint *v, uint *k)
{
     uint y=v[0], z=v[1], sum=0, i;         /* set up */
     uint delta=0x9e3779b9;                 /* a key schedule constant */
     uint a=k[0], b=k[1], c=k[2], d=k[3];   /* cache key */

     for (i=0; i < 32; i++) {                        /* basic cycle start */
         sum += delta;
         y += ((z<<4) + a) ^ (z + sum) ^ ((z>>5) + b);
         z += ((y<<4) + c) ^ (y + sum) ^ ((y>>5) + d);/* end cycle */
     }
     v[0]=y;
     v[1]=z;
}

void TEA_Encrypt(uint *v, uint *k)
{
    uint y=v[0], z=v[1], sum=0xC6EF3720, i; /* set up */
    uint delta=0x9e3779b9;                  /* a key schedule constant */
    uint a=k[0], b=k[1], c=k[2], d=k[3];    /* cache key */
     for(i=0; i<32; i++) {                            /* basic cycle start */
         z -= ((y<<4) + c) ^ (y + sum) ^ ((y>>5) + d);
         y -= ((z<<4) + a) ^ (z + sum) ^ ((z>>5) + b);
         sum -= delta;                                /* end cycle */
     }
     v[0]=y;
     v[1]=z;
}
uint m_pkey1_t[8];
uint m_pkey2_t[8];

void SetKey1(uint a1,uint a2,uint a3,uint a4,uint b1,uint b2,uint b3,uint b4)
{ 
	m_pkey1_t[0] =a1;	 m_pkey1_t[1] =a2;
	m_pkey1_t[2] =a3;	 m_pkey1_t[3] =a4; 

	m_pkey1_t[4] = b1; m_pkey1_t[5] = b2;
	m_pkey1_t[6] = b3; m_pkey1_t[7] = b4; 
}

void SetKey2(uint a1,uint a2,uint a3,uint a4,uint b1,uint b2,uint b3,uint b4)
{ 
	m_pkey2_t[0] =a1;	 m_pkey2_t[1] =a2;
	m_pkey2_t[2] =a3;	 m_pkey2_t[3] =a4; 

	m_pkey2_t[4] = b1; m_pkey2_t[5] = b2;
	m_pkey2_t[6] = b3; m_pkey2_t[7] = b4; 
}


inline int Decrypt_1(char *pbuf,int iszie) 
{
    int iminsize = sizeof(uint )/sizeof(char);
	int irunnum = iszie/(4*iminsize);
	int ilastnum = iszie%(4*iminsize);
    uint *prunbuf1 =(uint *)pbuf;
	int iadd = ilastnum>0?1:0;
	for(int i=0;i<irunnum+iadd;i++)
	{ 
		TEA_Decrypt(prunbuf1,m_pkey1_t);
		prunbuf1 =prunbuf1+2; 
		TEA_Decrypt(prunbuf1,m_pkey1_t+4);
		prunbuf1 =prunbuf1+2;
	} 
	return (irunnum + iadd)*4*iminsize;
}

inline int Encrypt_1(char *pbuf,int iszie)
{
    int iminsize = sizeof(uint )/sizeof(char);
    int irunnum = iszie/(4*iminsize);
    int ilastnum = iszie%(4*iminsize);

    uint *prunbuf1 =(uint *)pbuf;
    int iadd = ilastnum>0?1:0;
    for(int i=0;i<irunnum+iadd;i++)
    {
        TEA_Encrypt(prunbuf1,m_pkey1_t);
        prunbuf1 =prunbuf1+2;
        TEA_Encrypt(prunbuf1,m_pkey1_t+4);
        prunbuf1 =prunbuf1+2;
    }
    return (irunnum + iadd)*4*iminsize;
}
//

inline int Decrypt_2(char *pbuf,int iszie) 
{
    int iminsize = sizeof(uint )/sizeof(char);
	int irunnum = iszie/(4*iminsize);
	int ilastnum = iszie%(4*iminsize);
    uint *prunbuf1 =(uint *)pbuf;
	int iadd = ilastnum>0?1:0;
	for(int i=0;i<irunnum+iadd;i++)
	{ 
		TEA_Decrypt(prunbuf1,m_pkey2_t);
		prunbuf1 =prunbuf1+2; 
		TEA_Decrypt(prunbuf1,m_pkey2_t+4);
		prunbuf1 =prunbuf1+2;
	} 
	return (irunnum + iadd)*4*iminsize;
}

inline int Encrypt_2(char *pbuf,int iszie)
{
    int iminsize = sizeof(uint )/sizeof(char);
    int irunnum = iszie/(4*iminsize);
    int ilastnum = iszie%(4*iminsize);

    uint *prunbuf1 =(uint *)pbuf;
    int iadd = ilastnum>0?1:0;
    for(int i=0;i<irunnum+iadd;i++)
    {
        TEA_Encrypt(prunbuf1,m_pkey2_t);
        prunbuf1 =prunbuf1+2;
        TEA_Encrypt(prunbuf1,m_pkey2_t+4);
        prunbuf1 =prunbuf1+2;
    }
    return (irunnum + iadd)*4*iminsize;
}

inline int Encrypt(char *pbuf,int isize)
{
    Encrypt_1(pbuf,isize);
    return Encrypt_2(pbuf,isize);
}

inline int Decrypt(char *pbuf,int isize)
{
	Decrypt_2(pbuf,isize);
	return Decrypt_1(pbuf,isize);
}

//Execute My Function
//###########################################################################
//Myfunction.h head file is generated by the My_function Project.

#include "myfunction.h"

#ifndef WIN32 // or something like that...
#define __stdcall
#endif
//#define _founc(x)				myfunction_##x##_code
//#define _founc_len(x)			myfunction_##x##_code_LEN

unsigned char  p_my_function_[1024];
unsigned char  p_my_function2_[1024];

unsigned char  p_my_function[1024];
unsigned char  p_my_function2[1024];


//////////////////////////////////////////////////////////////////////////
//
//void ( __stdcall *_my_function1)(uint *v, uint *k );
//void ( __stdcall *_my_function2)(uint *v, uint *k );

//void ( __stdcall *_my_function1_)(uint *v,  uint *k  );
//void ( __stdcall *_my_function2_)(uint *v,  uint *k  );


inline int Decrypt_1_(char *pbuf,int iszie) 
{
    int iminsize = sizeof(uint )/sizeof(char);
	int irunnum = iszie/(4*iminsize);
	int ilastnum = iszie%(4*iminsize);
    uint *prunbuf1 =(uint *)pbuf;
	int iadd = ilastnum>0?1:0;
	for(int i=0;i<irunnum+iadd;i++)
	{ 
        TEA_Decrypt(prunbuf1,m_pkey1_t);
		prunbuf1 =prunbuf1+2; 
        TEA_Decrypt(prunbuf1,m_pkey1_t+4);
		prunbuf1 =prunbuf1+2;
	} 
	return (irunnum + iadd)*4*iminsize;
}

inline int Encrypt_1_(char *pbuf,int iszie)
{ 
    int iminsize = sizeof(uint )/sizeof(char);
	int irunnum = iszie/(4*iminsize);
	int ilastnum = iszie%(4*iminsize);

    uint *prunbuf1 =(uint *)pbuf;
	int iadd = ilastnum>0?1:0;
	for(int i=0;i<irunnum+iadd;i++)
	{ 
        TEA_Encrypt(prunbuf1,m_pkey1_t);
		prunbuf1 =prunbuf1+2; 
        TEA_Encrypt(prunbuf1,m_pkey1_t+4);
		prunbuf1 =prunbuf1+2;
	}
	return (irunnum + iadd)*4*iminsize;
} 


inline int Decrypt_2_(char *pbuf,int iszie) 
{
    int iminsize = sizeof(uint )/sizeof(char);
	int irunnum = iszie/(4*iminsize);
	int ilastnum = iszie%(4*iminsize);
    uint *prunbuf1 =(uint *)pbuf;
	int iadd = ilastnum>0?1:0;
	for(int i=0;i<irunnum+iadd;i++)
	{ 
        TEA_Decrypt(prunbuf1,m_pkey2_t);
		prunbuf1 =prunbuf1+2; 
        TEA_Decrypt(prunbuf1,m_pkey2_t+4);
		prunbuf1 =prunbuf1+2;
	} 
	return (irunnum + iadd)*4*iminsize;
}

inline int Encrypt_2_(char *pbuf,int iszie)
{ 
    int iminsize = sizeof(uint )/sizeof(char);
	int irunnum = iszie/(4*iminsize);
	int ilastnum = iszie%(4*iminsize);

    uint *prunbuf1 =(uint *)pbuf;
	int iadd = ilastnum>0?1:0;
	for(int i=0;i<irunnum+iadd;i++)
	{ 
        TEA_Encrypt(prunbuf1,m_pkey2_t);
		prunbuf1 =prunbuf1+2; 
        TEA_Encrypt(prunbuf1,m_pkey2_t+4);
		prunbuf1 =prunbuf1+2;
	}
	return (irunnum + iadd)*4*iminsize;
} 

int CxConnection::Encrypt_(char *pbuf,int isize)
{
	Encrypt_1_(pbuf,isize);
	return Encrypt_2_(pbuf,isize);
}
int CxConnection::Decrypt_(char *pbuf,int isize)
{
	Decrypt_2_(pbuf,isize);
	return Decrypt_1_(pbuf,isize);
}
 

//////////////////////////////////////////////////////////////////////////
//0: Load Key
void Load_my_key()
{
	SetKey1(0,0,0,0,0,0,0,0);
	SetKey2(0,0,0,0,0,0,0,0);

    uint pkey1[8];
    uint pkey2[8];

    memcpy(pkey1,Encode1,sizeof(uint)*8);
    memcpy(pkey2,Encode2,sizeof(uint)*8);

    Decrypt((char*)pkey1,sizeof(uint)*8);
    Decrypt((char*)pkey2,sizeof(uint)*8);

    memcpy(m_pkey1_t,pkey1,sizeof(uint)*8);
    memcpy(m_pkey2_t,pkey2,sizeof(uint)*8);
}

//1: Load myfunction. 
void Load_my_function()
{
#ifdef win32
	int code_len=myfunction1_CODE_T_LEN;
	char* pcode=( char*)malloc((code_len+100)*sizeof(  char));
	char* pecode=( char*)malloc((code_len+100)*sizeof(  char));
	int p;
	int hp=0;
	for(p=0;p<myfunction1_CODE_T_LEN;p++) 
		pcode[hp+p]=myfunction1_00001_code[p];
	hp=hp+p;

	Decrypt(pcode,myfunction1_CODE_T_LEN);
	//Note:here just is a simple encryption algorithm,you should replace it with your own.
	//There are a lot of encryption algorithms which you can get from the Internet.		
	for(int i=0;i<code_len;i++) 
		pecode[i]=pcode[i]^99;

	for(int i=0;i<myfunction1_00001_code_LEN;i++)
	{
		p_my_function_[i] = pecode[i];
	}

	int code_len2=myfunction2_00001_code_LEN;
	char* pcode2=(char*)malloc((code_len2+100)*sizeof(char));
	char* pecode2=(char*)malloc((code_len2+100)*sizeof(char));

	int p2;
	int hp2=0;
	for(p2=0;p2<myfunction2_00001_code_LEN;p2++) pcode2[hp2+p2]=myfunction2_00001_code[p2];
	hp2=hp2+p2;

	Decrypt(pcode2,myfunction2_CODE_T_LEN);
	//Note:here just is a simple encryption algorithm,you should replace it with your own.
	//There are a lot of encryption algorithms which you can get from the Internet.		
	for(int i=0;i<code_len2;i++) 
		pecode2[i]=pcode2[i]^99;

	for(int i=0;i<myfunction2_00001_code_LEN;i++)
	{
		p_my_function2_[i] = pecode2[i];
	} 
    _my_function1_=(void ( __stdcall *)(uint *v,
        uint *k
		)) &p_my_function_[0];

    _my_function2_=(void ( __stdcall *)(uint *v,
        uint *k
		)) &p_my_function2_[0];

#endif


} 
//1: Load myfunction. 
void Load_my_function2()
{ 
#ifdef win32
	int code_len=myfunction3_CODE_T_LEN;
	char* pcode=( char*)malloc((code_len+100)*sizeof(  char));
	char* pecode=( char*)malloc((code_len+100)*sizeof(  char));
	int p;
	int hp=0;
	for(p=0;p<myfunction3_CODE_T_LEN;p++) 
		pcode[hp+p]=myfunction1_00001_code[p];
	hp=hp+p;

	Decrypt(pcode,myfunction3_CODE_T_LEN);
	//Note:here just is a simple encryption algorithm,you should replace it with your own.
	//There are a lot of encryption algorithms which you can get from the Internet.		
	for(int i=0;i<code_len;i++) 
		pecode[i]=pcode[i]^99;

	for(int i=0;i<myfunction3_00001_code_LEN;i++)
	{
		p_my_function[i] = pecode[i];
	}


	int code_len2=myfunction4_00001_code_LEN;
	char* pcode2=(  char*)malloc((code_len2+100)*sizeof(  char));
	char* pecode2=(  char*)malloc((code_len2+100)*sizeof(  char));
	int p2;
	int hp2=0;
	for(p2=0;p2<myfunction4_00001_code_LEN;p2++) pcode2[hp2+p2]=myfunction2_00001_code[p2];
	hp2=hp2+p2;

	Decrypt(pcode2,myfunction4_CODE_T_LEN);
	//Note:here just is a simple encryption algorithm,you should replace it with your own.
	//There are a lot of encryption algorithms which you can get from the Internet.		
	for(int i=0;i<code_len2;i++) 
		pecode2[i]=pcode2[i]^99;

	for(int i=0;i<myfunction4_00001_code_LEN;i++)
	{
		p_my_function2[i] = pecode2[i];
	}
    _my_function1=(void ( __stdcall *)(uint *v, uint *k )) &p_my_function[0];
    _my_function2=(void ( __stdcall *)(uint *v, uint *k )) &p_my_function2[0];
#endif

} 
//2:Execute my function.
void Run_my_function()
{
	char str_a[70]=" HELLO MY_FOUNCTION1234567890abcdefghijklmnopqrstuvwxyzcxvisiontest!";//�������ַ�
	char str_k[70]="key Hello my_function 1234567890ABCDEFGcxvisiontest1122233344455566!";//�����ֵ䣨ͬ���ȣ�


    TEA_Encrypt(((uint*)str_a),((uint*)str_k) );
//    TEA_Encrypt(((uint*)str_a)+1,((uint*)str_k)+1);
//    TEA_Encrypt(((uint*)str_a)+2,((uint*)str_k)+2);
//    TEA_Encrypt(((uint*)str_a)+3,((uint*)str_k)+3);
//    TEA_Encrypt(((uint*)str_a)+4,((uint*)str_k)+4);
//	AfxMessageBox(str_a);


//    TEA_Decrypt(((uint*)str_a)+4,((uint*)str_k)+4);
//    TEA_Decrypt(((uint*)str_a)+3,((uint*)str_k)+3);
//    TEA_Decrypt(((uint*)str_a)+2,((uint*)str_k)+2);
//    TEA_Decrypt(((uint*)str_a)+1,((uint*)str_k)+1);
    TEA_Decrypt((uint*)str_a,(uint*)str_k);
//	AfxMessageBox(str_a);
}

void Run_my_function_()
{ 

    //void ( __stdcall *_my_function1_)(uint *v,
    //	uint *k
	//	);

    //_my_function1_=(void ( __stdcall *)(uint *v,
    //	uint *k
	//	)) &p_my_function_[0];

	//
    //void ( __stdcall *_my_function2_)(uint *v,
    //	uint *k
	//	);

    //_my_function2_=(void ( __stdcall *)(uint *v,
    //	uint *k
	//	)) &p_my_function2_[0];
	
	char str_a[70]=" HELLO MY_FOUNCTION1234567890abcdefghijklmnopqrstuvwxyzcxvisiontest!";//�������ַ�
	char str_k[70]="key Hello my_function 1234567890ABCDEFGcxvisiontest1122233344455566!";//�����ֵ䣨ͬ���ȣ�

    //_my_function1_(((uint*)str_a),((uint*)str_k) );
    //_my_function1_(((uint*)str_a)+1,((uint*)str_k)+1);
    //_my_function1_(((uint*)str_a)+2,((uint*)str_k)+2);
    //_my_function1_(((uint*)str_a)+3,((uint*)str_k)+3);
    //_my_function1_(((uint*)str_a)+4,((uint*)str_k)+4);

//    Encrypt_1_(str_a,70);
CxConnection::Encrypt_(str_a,70);
//	AfxMessageBox(str_a);

    //_my_function2_(((uint*)str_a)+4,((uint*)str_k)+4);
    //_my_function2_(((uint*)str_a)+3,((uint*)str_k)+3);
    //_my_function2_(((uint*)str_a)+2,((uint*)str_k)+2);
    //_my_function2_(((uint*)str_a)+1,((uint*)str_k)+1);
    //_my_function2_((uint*)str_a,(uint*)str_k);
  // Decrypt_1_(str_a,70);

   CxConnection::Decrypt_(str_a,70);
//	AfxMessageBox(str_a);
}

 
//###########################################################################
//////////////////////////////////////////////////////////////////////////////
////1: Load myfunction. 
//
void CxConnection::TestA()
{
	char str_a[70]=" HELLO MY_FOUNCTION1234567890abcdefghijklmnopqrstuvwxyzcxvisiontest!";//�������ַ�

	CxEncrypt(str_a,60);
	CxDecrypt(str_a,60);
}
void CxConnection::Loadmyfunction()
{ 
 

    Load_my_function();	//Decrypt
Run_my_function();

	Run_my_function_();//test 1
	Load_my_function2();//Decrypt

	Load_my_key();
	Run_my_function();//Execute
	SetKey1(0,0,0,0,0,0,0,0);
	SetKey2(0,0,0,0,0,0,0,0);
	//Run_my_function();	//Execute

//	int code_len=myfunction_00001_code_LEN;
//	unsigned char* pcode=(unsigned char*)malloc(code_len*sizeof(unsigned char));
//	int p;
//	int hp=0;
//	for(p=0;p<_founc_len(00001);p++) pcode[hp+p]=_founc(00001)[p];
//	hp=hp+p;
//
//	//Note:here just is a simple encryption algorithm,you should replace it with your own.
//	//There are a lot of encryption algorithms which you can get from the Internet.		
//	for(int i=0;i<code_len;i++) 
//		p_my_function[i]=pcode[i]^99;
//	int code_len2=myfunction_00002_code_LEN;
//	unsigned char* pcode2=(unsigned char*)malloc(code_len2*sizeof(unsigned char));
//	int p2;
//	int hp2=0;
//	for(p2=0;p2<_founc_len(00002);p2++) pcode2[hp2+p2]=_founc(00002)[p2];
//	hp2=hp2+p2;
//	
//	//Note:here just is a simple encryption algorithm,you should replace it with your own.
//	//There are a lot of encryption algorithms which you can get from the Internet.		
//
//	for(int i=0;i<code_len2;i++) 
//		p_my_function2[i]=pcode2[i]^99;
//		
//		
//
//
//	_my_function=(void ( __stdcall *)(uint *v,
//		uint *k)) &p_my_function[0];
//
//	_my_function2=(void ( __stdcall *)(uint *v,
//		uint *k)) &p_my_function2[0];
//
} 
//void CxConnection::Run_my_function_()
//{ 
//
//	char str_a[70]=" HELLO MY_FOUNCTION1234567890abcdefghijklmnopqrstuvwxyzcxvisiontest!";//�������ַ�
//	char str_k[70]="key Hello my_function 1234567890ABCDEFGcxvisiontest1122233344455566!";//�����ֵ䣨ͬ���ȣ�
//
//	_my_function1_(((uint*)str_a),((uint*)str_k) );
//	_my_function1_(((uint*)str_a)+1,((uint*)str_k)+1);
//	_my_function1_(((uint*)str_a)+2,((uint*)str_k)+2);
//	_my_function1_(((uint*)str_a)+3,((uint*)str_k)+3);
//	_my_function1_(((uint*)str_a)+4,((uint*)str_k)+4);
//	//AfxMessageBox(str_a);
//
//	_my_function2_(((uint*)str_a)+4,((uint*)str_k)+4);
//	_my_function2_(((uint*)str_a)+3,((uint*)str_k)+3);
//	_my_function2_(((uint*)str_a)+2,((uint*)str_k)+2);
//	_my_function2_(((uint*)str_a)+1,((uint*)str_k)+1);
//	_my_function2_((uint*)str_a,(uint*)str_k);
//	//AfxMessageBox(str_a);
//}
////2:Execute my function.
inline int CxConnection::CxDecrypt_2(char *pbuf,int isize) 
{
    int iminsize = sizeof(uint )/sizeof(char);
	int irunnum = isize/(4*iminsize);
	int ilastnum = isize%(4*iminsize);

    uint *prunbuf1 =(uint *)pbuf;
	int iadd = ilastnum>0?1:0;
	for(int i=0;i<irunnum+iadd;i++)
	{
		//TEA_Decrypt(prunbuf1,m_pkey);
        TEA_Decrypt(prunbuf1,m_pkey2);
		prunbuf1 =prunbuf1+2;
		//TEA_Decrypt(prunbuf1,m_pkey+6);
        TEA_Decrypt(prunbuf1,m_pkey2+4);
		prunbuf1 =prunbuf1+2;
	}

	return (irunnum + iadd)*4*iminsize;
}

inline int CxConnection::CxEncrypt_2(char *pbuf,int isize)
{ 
    int iminsize = sizeof(uint )/sizeof(char);
	int irunnum = isize/(4*iminsize);
	int ilastnum = isize%(4*iminsize);

    uint *prunbuf1 =(uint *)pbuf;
	int iadd = ilastnum>0?1:0;
	for(int i=0;i<irunnum+iadd;i++)
	{
		//TEA_Encrypt(prunbuf1,m_pkey);
        TEA_Encrypt(prunbuf1,m_pkey2);
		prunbuf1 =prunbuf1+2;
		//TEA_Encrypt(prunbuf1,m_pkey+6);
        TEA_Encrypt(prunbuf1,m_pkey2+4);
		prunbuf1 =prunbuf1+2;
	}
	return (irunnum + iadd)*4*iminsize;

} 

inline int CxConnection::CxDecrypt_1(char *pbuf,int isize) 
{
    int iminsize = sizeof(uint )/sizeof(char);
	int irunnum = isize/(4*iminsize);
	int ilastnum = isize%(4*iminsize);

    uint *prunbuf1 =(uint *)pbuf;
	int iadd = ilastnum>0?1:0;
	for(int i=0;i<irunnum+iadd;i++)
	{
		//TEA_Decrypt(prunbuf1,m_pkey);
        TEA_Decrypt(prunbuf1,m_pkey1);
		prunbuf1 =prunbuf1+2;
		//TEA_Decrypt(prunbuf1,m_pkey+6);
        TEA_Decrypt(prunbuf1,m_pkey1+4);
		prunbuf1 =prunbuf1+2;
	}

	return (irunnum + iadd)*4*iminsize;
}

inline int CxConnection::CxEncrypt_1(char *pbuf,int isize)
{ 
    int iminsize = sizeof(uint )/sizeof(char);
	int irunnum = isize/(4*iminsize);
	int ilastnum = isize%(4*iminsize);

    uint *prunbuf1 =(uint *)pbuf;
	int iadd = ilastnum>0?1:0;
	for(int i=0;i<irunnum+iadd;i++)
	{
		//TEA_Encrypt(prunbuf1,m_pkey);
        TEA_Encrypt(prunbuf1,m_pkey1);
		prunbuf1 =prunbuf1+2;
		//TEA_Encrypt(prunbuf1,m_pkey+6);
        TEA_Encrypt(prunbuf1,m_pkey1+4);
		prunbuf1 =prunbuf1+2;
	}
	return (irunnum + iadd)*4*iminsize;

} 

inline int CxConnection::CxDecrypt(char *pbuf,int isize) 
{
	CxDecrypt_2(pbuf,isize);
	return CxDecrypt_1(pbuf,isize);
    //int iminsize = sizeof(uint )/sizeof(char);
	//int irunnum = iszie/(4*iminsize);
	//int ilastnum = iszie%(4*iminsize);

    //uint *prunbuf1 =(uint *)pbuf;
	//int iadd = ilastnum>0?1:0;
	//for(int i=0;i<irunnum+iadd;i++)
	//{
	//	//TEA_Decrypt(prunbuf1,m_pkey);
	//	_my_function2(prunbuf1,m_pkey);
	//	prunbuf1 =prunbuf1+2;
	//	//TEA_Decrypt(prunbuf1,m_pkey+6);
	//	_my_function2(prunbuf1,m_pkey+6);
	//	prunbuf1 =prunbuf1+2;
	//}
	//
	//return (irunnum + iadd)*4*iminsize;
}

inline int CxConnection::CxEncrypt(char *pbuf,int isize)
{ 
 	CxEncrypt_1(pbuf,isize);
 	return CxEncrypt_2(pbuf,isize);
    //int iminsize = sizeof(uint )/sizeof(char);
	//int irunnum = iszie/(4*iminsize);
	//int ilastnum = iszie%(4*iminsize);

    //uint *prunbuf1 =(uint *)pbuf;
	//int iadd = ilastnum>0?1:0;
	//for(int i=0;i<irunnum+iadd;i++)
	//{
	//	//TEA_Encrypt(prunbuf1,m_pkey);
	//	_my_function1(prunbuf1,m_pkey);
	//	prunbuf1 =prunbuf1+2;
	//	//TEA_Encrypt(prunbuf1,m_pkey+6);
	//	_my_function1(prunbuf1,m_pkey+6);
	//	prunbuf1 =prunbuf1+2;
	//}
	//return (irunnum + iadd)*4*iminsize;

} 
inline int CxEncrypt_(char *pbuf,int isize)
{
	Encrypt_1_(pbuf,isize);
	return Encrypt_2_(pbuf,isize);
}

inline int CxDecrypt_(char *pbuf,int isize)
{
	Decrypt_2_(pbuf,isize);
	return Decrypt_1_(pbuf,isize);
}





//void ExKeyA()
//{
//	memcpy(m_pkeynew,m_pkey,sizeof(uint)*12);
//	memcpy(m_pkey,m_pkeyold,sizeof(uint)*12);
//}
//void ExKeyB()
//{
//	memcpy(m_pkey,m_pkeynew,sizeof(uint)*12);
//}
void CxConnection::SetKey(long a1,long a2,long a3,long a4,long b1,long b2,long b3,long b4,
							long c1,long c2,long c3,long c4,long d1,long d2,long d3,long d4)
{ 
	m_pkey1[0] =a1;	 m_pkey1[1] =a2;
	m_pkey1[2] =a3;	 m_pkey1[3] =a4;
	m_pkey1[4] =b1;	 m_pkey1[5] =b2;
	m_pkey1[6] =b3;  m_pkey1[7] =b4; 

	m_pkey2[0] =c1;	 m_pkey2[1] =c2;
	m_pkey2[2] =c3;	 m_pkey2[3] =c4;
	m_pkey2[4] =d1;	 m_pkey2[5] =d2;
	m_pkey2[6] =d3;  m_pkey2[7] =d4; 
	
	//ShowLog(tr("DEBUG KEY %1 %2 %3 %4 %5 %6 %7 %8 %9 %10 %11 %12 %13 %14 %15 %16 " ).arg(a1).arg(a2).arg(a3).arg(a4)
	//.arg(b1).arg(b2).arg(b3).arg(b4)
	//.arg(c1).arg(c2).arg(c3).arg(c4)
	//.arg(d1).arg(d2).arg(d3).arg(d4));

}
//void SetOldKey(long a1,long a2,long a3,long a4,long a5,long a6,long b1,long b2,long b3,long b4,long b5,long b6)
//{ 
//	m_pkeyold[0] =a1;	 m_pkeyold[1] =a2;
//	m_pkeyold[2] =a3;	 m_pkeyold[3] =a4;
//	m_pkeyold[4] =a5;	 m_pkeyold[5] =a6;	
//	m_pkeyold[6] = b1; m_pkeyold[7] = b2;
//	m_pkeyold[8] = b3;	 m_pkeyold[9] = b4;
//	m_pkeyold[10] =b5;	 m_pkeyold[11] =b6;
//}
//void LoadKey(char *pKey,int ilen)
//{
//	int iminsize = sizeof(uint)/sizeof(char);
//	int isize = ilen/iminsize;
//	memset(m_pkey,0,sizeof(uint)*12);
//	//m_pkey = new uint[12];
//	if(isize>12)
//	{
//		memcpy((char*)m_pkey,(char*)pKey,12*iminsize);
//	}
//	else
//	{
//		memcpy((char*)m_pkey,(char*)pKey,ilen);
//	} 
//}
//void TimeKey()
//{
//	int iminsize = sizeof(uint)/sizeof(char);
//	QDateTime now = QDateTime::currentDateTime();
//
//	QString stnowtime = now.toString(QLatin1String("yyyyMMdd"));
//	
//	//SYSTEMTIME st;
//	//GetLocalTime(&st);
//	//char LocalTime_time[16];
//	//ZeroMemory(LocalTime_time,sizeof(unsigned char)*8);
//	//sprintf(LocalTime_time,"%4d%02d%02d",st.wYear,st.wMonth,st.wDay);
//
//	memset(m_pkey,0,sizeof(uint)*12);
//	memcpy((char*)m_pkey,stnowtime.toLocal8Bit(),12*iminsize);
//}
//void TimeKeyUSER(QString user)
//{
//	int iminsize = sizeof(uint)/sizeof(char);
//	QDateTime now = QDateTime::currentDateTime();
//
//	QString stnowtime = now.toString(QLatin1String("yyyyMMdd")) + user;
// 
//
//	//memset(m_pkey,0,sizeof(uint)*12);
//	//if(stnowtime.size()>=12*iminsize)
//	//memcpy((char*)m_pkey,stnowtime.toLocal8Bit(),12*iminsize);
//	//else
//	//memcpy((char*)m_pkey,stnowtime.toLocal8Bit(),stnowtime.size());
//}
//////////////////////////////////////////////////////////////////////////
/// \brief CxConnection::CxConnection
/// \param parent
/// \param pdialog
/// \param icos
///
///
CxConnection::CxConnection(Dialog *pdialog)
{
    m_Pmap = pdialog->getpmap();
    m_Dmap = pdialog->getdmap();
    m_Fmap = pdialog->getfmap();

    //m_icontinuefail = 0;
    m_irecaltimes = 0;

    m_pattachconnect = NULL;


    setdatafree();
    setdutyfree();

    m_iuserclass = 0;



    m_pdialog = pdialog;
    m_user = tr("");
    m_greetingMessage = tr("undefined");

    CxConnection::setgreetingusername( tr("unknown"));
    CxConnection::setstate(CxConnection::WaitingForGreeting);
    CxConnection::setdatetype(CxConnection::Undefined);
    CxConnection::setbytesfordatenum(-1);
    setcustomtype(true);
    m_bencrypt = false;
    //transferTimerId = 0;
    isGreetingMessageSent = false;

    QDateTime now = QDateTime::currentDateTime();
    QString qyear = now.toString(QLatin1String("yyyy"));
    QString qmh = now.toString(QLatin1String("MM"));
    QString qdy = now.toString(QLatin1String("dd"));
    int iy = qyear.toInt();
    int im = qmh.toInt();
    int id = qdy.toInt();

    int ip1 = 1;//alistparm.at(0).toInt();
    int ip2 = 2;//alistparm.at(1).toInt();
    int ip3 = 3;//alistparm.at(2).toInt();
    int ip4 = 4;//alistparm.at(3).toInt();
    int iport = 5;

    SetKey(id,im,id,id,
            im,id,id,im,
            im,id,im,id,
            id,im,id,id);
    TestA();
   // m_reconnectTimer.setInterval(8 * 1000);
   // connect(&m_reconnectTimer, SIGNAL(timeout()), this, SLOT(restart()));
    m_bencrypt = false;
    setcustomtype(true);
}
CxConnection::CxConnection(QTcpSocket *parent,Dialog *pdialog,int icos)
{
    m_Pmap = pdialog->getpmap();
    m_Dmap = pdialog->getdmap();
    m_Fmap = pdialog->getfmap();

    //m_icontinuefail = 0;
	m_irecaltimes = 0;

	m_pattachconnect = NULL;
	
    setdatafree();
    setdutyfree();

	m_iuserclass = 0;
	m_cos = icos;
	m_psocket = parent;
	//m_peerAddress = parent->peerAddress().toString();
	
	m_pdialog = pdialog;
	m_user = tr("");
    m_greetingMessage = tr("undefined");

    CxConnection::setgreetingusername( tr("unknown"));
    CxConnection::setstate(CxConnection::WaitingForGreeting);

    CxConnection::setdatetype(CxConnection::Undefined);
    CxConnection::setbytesfordatenum(-1);
m_bencrypt = false;
setcustomtype(true);
    //transferTimerId = 0;
    isGreetingMessageSent = false;
 
 	QDateTime now = QDateTime::currentDateTime();
	QString qyear = now.toString(QLatin1String("yyyy"));
	QString qmh = now.toString(QLatin1String("MM"));
	QString qdy = now.toString(QLatin1String("dd"));
	int iy = qyear.toInt();
	int im = qmh.toInt();
	int id = qdy.toInt();
    QString qsip4=  getio_local_address_string();//m_psocket->localAddress().toString();
	QStringList	alistparm  = qsip4.split(QLatin1String("."));	
	int ip1 = 1;//alistparm.at(0).toInt();
	int ip2 = 2;//alistparm.at(1).toInt();
	int ip3 = 3;//alistparm.at(2).toInt();
	int ip4 = 4;//alistparm.at(3).toInt();
    int iport = 5;
 
	SetKey(id,im,id,id,
			im,id,id,im,
			im,id,im,id,
			id,im,id,id);

    TestA();

    QObject::connect(m_psocket, SIGNAL(readyRead()), this, SLOT(processReadyRead()));

    m_reconnectTimer.setInterval(8 * 1000);

	connect(&m_reconnectTimer, SIGNAL(timeout()), this, SLOT(restart()));

 }
CxConnection::CxConnection(Dialog *pdialog,QTcpSocket *parent)
{

    m_Pmap = pdialog->getpmap();
    m_Dmap = pdialog->getdmap();
    m_Fmap = pdialog->getfmap();
m_bencrypt = false;
setcustomtype(true);
   m_psocket = parent;

   m_cos = 1;

   m_pdialog = pdialog;
}
CxConnection::CxConnection(QTcpSocket *parent,Dialog *pdialog,int icos,int itemp)
{
    m_Pmap = pdialog->getpmap();
    m_Dmap = pdialog->getdmap();
    m_Fmap = pdialog->getfmap();

    m_irecaltimes = 0;

    m_pattachconnect = NULL;

    setdatafree();
    setdutyfree();

    m_iuserclass = 0;
    m_cos = icos;
    m_psocket = parent;

    m_pdialog = pdialog;
    m_user = tr("");
    m_greetingMessage = tr("undefined");

    CxConnection::setgreetingusername( tr("unknown"));
    CxConnection::setstate(CxConnection::WaitingForGreeting);
    CxConnection::setdatetype(CxConnection::Undefined);
    CxConnection::setbytesfordatenum(-1);
m_bencrypt = false;
setcustomtype(true);
    //transferTimerId = 0;
    isGreetingMessageSent = false;

    QDateTime now = QDateTime::currentDateTime();
    QString qyear = now.toString(QLatin1String("yyyy"));
    QString qmh = now.toString(QLatin1String("MM"));
    QString qdy = now.toString(QLatin1String("dd"));
    int iy = qyear.toInt();
    int im = qmh.toInt();
    int id = qdy.toInt();
    QString qsip4=  getio_local_address_string();//m_psocket->localAddress().toString();
    QStringList	alistparm  = qsip4.split(QLatin1String("."));
    int ip1 = 1;//alistparm.at(0).toInt();
    int ip2 = 2;//alistparm.at(1).toInt();
    int ip3 = 3;//alistparm.at(2).toInt();
    int ip4 = 4;//alistparm.at(3).toInt();
    int iport = 5;

    SetKey(id,im,id,id,
            im,id,id,im,
            im,id,im,id,
            id,im,id,id);
    TestA();
    QObject::connect(m_psocket, SIGNAL(readyRead()), this, SLOT(processReadyRead()));

   // m_reconnectTimer.setInterval(8 * 1000);

   // connect(&m_reconnectTimer, SIGNAL(timeout()), this, SLOT(restart()));

    //m_bencrypt = true;


}

void CxConnection::reconnect(QTcpSocket *parent,int icos)
{
    setdatafree();
    setdutyfree();
    ShowLog("reconnect connection reset");
	m_iuserclass = 0;
	m_cos = icos;
	m_psocket = parent;

//	m_pdialog = pdialog;
 
    CxConnection::setstate(CxConnection::WaitingForGreeting);
    CxConnection::setdatetype(CxConnection::Undefined);
    CxConnection::setbytesfordatenum(-1);

	//transferTimerId = 0;
	isGreetingMessageSent = false;

	QDateTime now = QDateTime::currentDateTime();
	QString qyear = now.toString(QLatin1String("yyyy"));
	QString qmh = now.toString(QLatin1String("MM"));
	QString qdy = now.toString(QLatin1String("dd"));
	int iy = qyear.toInt();
	int im = qmh.toInt();
	int id = qdy.toInt();
    QString qsip4= getio_local_address_string();//m_psocket->localAddress().toString();
	QStringList	alistparm  = qsip4.split(QLatin1String("."));	
	int ip1 = 1;//alistparm.at(0).toInt();
	int ip2 = 2;//alistparm.at(1).toInt();
	int ip3 = 3;//alistparm.at(2).toInt();
	int ip4 = 4;//alistparm.at(3).toInt();
    int iport = 5;



	SetKey(id,im,id,id,
		im,id,id,im,
		im,id,im,id,
		id,im,id,id);

	QObject::connect(m_psocket, SIGNAL(readyRead()), this, SLOT(processReadyRead()));

}
void CxConnection::connectstart()
{

    CxConnection::setgreetingusername(getio_peer_address_string() + ':'+ QString::number(iopeerport()));
    CxConnection::ShowLog(tr("Greet:")+CxConnection::getgreetingusername());
    CxConnection::setdatetype(CxConnection::Undefined);
    CxConnection::setbytesfordatenum(0);

    CxConnection::getconnectbuf().clear();
    CxConnection::LoginUSER(this);//set user name in client Greet

    SetKey(0,0,0,0,
            0,0,0,0,
            0,0,0,0,
            0,0,0,0);

    m_irestarttimes = 0;

    setstate(ConnectionState::ReadyForUse);
}
void CxConnection::connectisok(int iconnectsum)
{ 
	m_irestarttimes = 0;
    m_peerAddress = getio_peer_address_string();//m_psocket->peerAddress().toString();
    if(iovalid())//m_psocket->isValid())
	{
		if(m_cos==0)//client
		{
			if(m_user == tr(""))
			{
				QString qstrtime = QTime::currentTime().toString("Chhmmsszzz");
				//m_user = ;
				SetUser(m_pdialog->getadminuser() + qstrtime);
			}
			ShowLog(tr("user:")+m_user); 
			m_greetingMessage = m_user;
		}
        if(false==getcustomtype())
        sendGreetingMessage();
	} 

    CxConnection::getdutytimer().start(20, this);
	
	 
}
void CxConnection::overconnect()
{

	m_iuserclass = 0;

    CxConnection::getdutytimer().stop();
    CxConnection::getpingtimer().stop();

    ioclose();
    deletesocket();
	m_pdialog->removeconnect(this);
    ShowLog("DisConnect");

    if(0==IScors())//client
		m_reconnectTimer.start();

}
void CxConnection::restart()
{	
	
	m_reconnectTimer.stop();

	if(m_cos==0)//client 
	{
		
//		if(CDog::DogLibraryisload())
		{
			QTcpSocket *ptcpClient = new QTcpSocket;
			//connect(m_ptcpClient, SIGNAL(connected()),this, SLOT(ClientIsConnection()));
			QHostAddress qaddress;

			QString serverip = m_pdialog->GetInputText();
			QString serverport = tr("82") ;
			QStringList	alistparm  =  serverip.split(QLatin1String(":"));
			if(alistparm.size()>=2)
			{
				 serverip = alistparm.at(0);
				 serverport = alistparm.at(1);
			}	

			if( serverip=="")
			{
                qaddress.setAddress(QLatin1String("192.168.1.2"));
                 serverip = QLatin1String("192.168.1.2");
				 serverport = tr("82");
                ShowLog(tr("connectaddress:192.168.1.2:82"));
			}
			else 
			{
				qaddress.setAddress( serverip);
				ShowLog(tr("connectaddress:")+ serverip+tr(":")+ serverport);
			}

			 
			 reconnect(ptcpClient,0);

 
			if( serverport!="")
				 connectToHost(qaddress, serverport.toInt());
			else
				 connectToHost(qaddress,82);


			const int Timeout = 10 * 1000;

			if (!ptcpClient->waitForConnected(Timeout)) 
			{
				overconnect(); 
				ShowLog(tr("retry No Connected"));
				m_irestarttimes  = m_irestarttimes  + 1;
				
				if(m_irestarttimes>30)
				{
					
				}
				//m_reconnectTimer.start();
				return;
			}
			else
				 connectisok();
			m_pdialog->ReFlashUSER();
		}
	}  
}
void CxConnection::deletesocket()
{
	if(m_psocket!=NULL)
		delete m_psocket;
	m_psocket =NULL;
}
CxConnection::~CxConnection()
{
	
	//if(m_preqbuff!=NULL)
	//	delete m_preqbuff;
}

void CxConnection::stoptimer()
{
    CxConnection::getdutytimer().stop();
}
//char pchar[1024*1024];
char g_pchar[TEMP_SIZE];
qint64 CxConnection::Ewrite(const QByteArray &data)
{
    if(false==m_bencrypt)
    {
         ShowLog(data.toStdString().c_str());
        int isize = iowrite(data);// m_psocket->write(data1);
        return isize;
    }
    else
    {
        int isize = data.size();
        memcpy(g_pchar,data.data(),isize);
        int iesize = CxEncrypt(g_pchar,isize);
        QByteArray data1(g_pchar,iesize);
        isize = iowrite(data1);// m_psocket->write(data1);

        return isize;
    }

}
QByteArray CxConnection::Eread(qint64 maxlen)
{ 
    QByteArray data = ioread(maxlen);// m_psocket->read(maxlen);
        if(false==m_bencrypt)
        {
            ShowLog(data.toStdString().c_str());
            return data;
        }
        else
        {

            int isize = data.size();
            memcpy(g_pchar,data.data(),isize);
            int iesize = CxDecrypt(g_pchar,isize);
            QByteArray data1(g_pchar,iesize) ;

            return data1;
        }
}
QByteArray CxConnection::EreadAll()
{
   return Eread(16);
}


QByteArray CxConnection::EnHeadFormatRand(QByteArray headmsg)
{
	int itotalsize = headmsg.size();

	int ilastsize = itotalsize%16;
 
	for(int j = ilastsize;j<16;j++)
	{
		//if(j==ilastsize)
		//headmsg += ' ';
		//else
		headmsg += (char)rand();
	} 
	return headmsg;
}
QByteArray CxConnection::EnHeadFormat(QByteArray headmsg)
{
	int itotalsize = headmsg.size();
	
	int ilastsize = itotalsize%16;
	//if(i>=16)
	//	return;//abort();
	for(int j = ilastsize;j<16;j++)
	{
		headmsg += ' ';
	} 
	return headmsg;
}
QByteArray CxConnection::EnHeadFormat2(QByteArray headmsg)
{
	int itotalsize = headmsg.size();

	int ilastsize = itotalsize%16;

	for(int j = ilastsize;j<16;j++)
	{
		headmsg = ' '+headmsg;
	} 
	return headmsg;
}
void CxConnection::relogin()
{
	QString cxname = "cxvision2016";
	QDateTime now = QDateTime::currentDateTime(); 
	QString qmh = now.toString(QLatin1String("MM"));
	QString qdy = now.toString(QLatin1String("dd"));

	QString qadmin =  cxname + qmh + qdy + ipstring;
	
	sendLogin(qadmin);	
}
void  CxConnection::SetUser(const QString &user)
{
	m_user = user;
}
QString CxConnection::name() const
{
    return CxConnection::getgreetingusername();
}
QString CxConnection::shortname() const
{
    return CxConnection::getgreetingusername().mid(16);
}

void CxConnection::setGreetingMessage(const QString &message)
{
	m_greetingMessage = message;
}

void CxConnection::sendIPKEY()
{
	QDateTime now = QDateTime::currentDateTime();
	QString qyear = now.toString(QLatin1String("yyyy"));
	QString qmh = now.toString(QLatin1String("MM"));
	QString qdy = now.toString(QLatin1String("dd"));
	int iy = qyear.toInt();
	int im = qmh.toInt();
	int id = qdy.toInt();
    QString qsip4= getio_local_address_string();// m_psocket->localAddress().toString();
	QStringList	alistparm  = qsip4.split(QLatin1String("."));	
	int ip1 =  alistparm.at(0).toInt();
	int ip2 =  alistparm.at(1).toInt();
	int ip3 =  alistparm.at(2).toInt();
	int ip4 =  alistparm.at(3).toInt();
    int iport = iolocalport();// m_psocket->localPort();
	sendCommand("setkey "+tr("%1,").arg(ip1)+tr("%1,").arg(ip2)+tr("%1,").arg(ip3)
		+tr("%1,").arg(ip4)+tr("%1").arg(iport));
	ipstring = alistparm[0] +alistparm[1] +alistparm[2] +alistparm[3] +tr("%1").arg(iport) ;
	
	SetKey(ip4,id,iport,ip4,
			id,im,iport,ip4,
			iport,id,iport,ip4,
			ip4,id,iport,ip4);

	
}
void CxConnection::sendpublicK(int ivalue1,int ivalue2,int ivalue3,int ivalue4,int ivalue5)
{
	sendCommand("rekey "+tr("%1,").arg(ivalue1)+tr("%1,").arg(ivalue2)+tr("%1,").arg(ivalue3)
		+tr("%1,").arg(ivalue4)+tr("%1").arg(ivalue5));
}

void CxConnection::sendPong()
{  
	QByteArray msg  =  RandSum().toUtf8();
	msg  = EnHeadFormat(msg);
	QByteArray data = "PONG " + QByteArray::number(msg.size()) + ' ' ;

	QByteArray dataf =  EnHeadFormatRand(data) + msg;
	Ewrite(dataf);


}
void CxConnection::sendGreetingMessage()
{

	QByteArray greeting = m_greetingMessage.toUtf8(); 
	greeting = EnHeadFormat(greeting);
	QByteArray data = "GREETING " + QByteArray::number(greeting.size()) + ' ' ;
	QByteArray dataf =  EnHeadFormat(data)+ greeting;
	if (Ewrite(dataf) == dataf.size())
		isGreetingMessageSent = true;
}
bool CxConnection::sendMessage(const QString &message)
{
    if (message.isEmpty())
        return false;

    QByteArray msg = message.toUtf8();
      msg = EnHeadFormat(msg);
    QByteArray data = "MESSAGE " + QByteArray::number(msg.size()) + ' ' ;
	QByteArray dataf =  EnHeadFormat(data) + msg ;
	return (Ewrite(dataf) == dataf.size());
 
}
bool CxConnection::sendLogin(const QString &message)
{
	if (message.isEmpty())
		return false;
	//SetUser(message);
	QByteArray msg = message.toUtf8();
	msg = EnHeadFormat(msg);
	QByteArray data = "LOGIN " + QByteArray::number(msg.size()) + ' ' ;
	QByteArray dataf =  EnHeadFormat(data) + msg ;
	return (Ewrite(dataf) == dataf.size());

}
bool CxConnection::sendLogok()
{
	//QByteArray data = "LOGOK " + QByteArray::number(0) + ' ' ;
	//
	//QByteArray dataf =  EnHeadFormat(data) ;
	//
	//return (Ewrite(dataf) == dataf.size());
	
	QByteArray msg  =  RandSum().toUtf8();
	msg  = EnHeadFormat(msg);
	QByteArray data = "LOGOK " + QByteArray::number(msg.size()) + ' ' ;
	QByteArray dataf =  EnHeadFormatRand(data) + msg;
	return Ewrite(dataf) == dataf.size();
	
}
bool CxConnection::sendCommand(const QString &message,const QString &stid)
{
	if (message.isEmpty())
		return false;

	QByteArray msg = (stid + message).toUtf8();
	msg = EnHeadFormat(msg);
	QByteArray data = "COMM " + QByteArray::number(msg.size()) + ' ' ;
	QByteArray dataf =  EnHeadFormat(data) + msg ;
	return (Ewrite(dataf) == dataf.size()); 
}
static qint64 g_lasttime = 1;
inline int CxConnection::sendpiecewaittime(int icp)
{
    qint64 itimes = m_apiece->m_ipiecestatus[icp];
	if(itimes>=0)	
    {
        if(0==itimes)
            m_apiece->m_ipiecestatus[icp] = g_lasttime + 1; //mark it

        qint64 icurtimeint = m_sendTime.elapsed();
        g_lasttime = icurtimeint;
		if(0==itimes)
		{
			m_apiece->m_ipiecestatus[icp] = icurtimeint;
			return 0;
		}
		else if(itimes>0)
		{
			int icurtimes = icurtimeint - itimes ;
			return icurtimes;
		}
	}
	else if(-1==itimes)
		return -1;

}
inline int CxConnection::piececanbesend(int icp)//1 can be transfer, 0 no be transfer
{  
	int ipasstime = sendpiecewaittime(icp);
	if(0== ipasstime)
	{
		return 1;
	}
	else if(ipasstime>=30000)//transfer over 30 s no finish to retransfer
	{
		return 1;
	} 
	else if(ipasstime<0)
		return 0;
	else if(ipasstime>0)
		return 0;
    else
        return 0;
}
void CxConnection::setsendfinish(int icp)
{
    m_apiece->m_ipiecestatus[icp] = -1;
}
qint64 CxConnection::getnextsend()
{ 
    for(qint64 i=0;i<m_apiece->m_ipiecesize;i++)
    {
        if(piececanbesend(i)>0)
        {
            return i;
        }
    }
    return -1;
}


QByteArray CxConnection::gemfieldCRC(QByteArray gemfield)
{
  
    unsigned long crc_32 = crc32x(0, 0, 0);
     crc_32 =  crc32x(crc_32, (const uchar *)gemfield.constData(), gemfield.length());
     char *pchar = (char *)&crc_32;
    QByteArray temp (pchar,2);//4

    return temp;
/*
        QByteArray temp;

        unsigned short crc = 0xffff;
        unsigned short a,j,k;
        for(a=0;a<gemfield.size();a++)
        {
            crc =crc ^ ( (int)gemfield.at(a)>=0 ?  gemfield.at(a) : (gemfield.at(a)+256) );
            for(j=0;j<8;j++)
            {
                k=crc & 01;
                crc = crc >> 1;
                if (k==0) continue;
                crc =crc ^ 0xA001;
            }
        }
        temp[1] = crc/256;
        temp[0] = crc%256;


        return temp;
 */
}

bool CxConnection::sendOnePiece(int ipiece,const QString &stid)
{
    if (m_pstrdata->isEmpty())
         return false;

    int icurpos = ipiece * m_apiece->pieceLength;
    m_apiece->icurpiece = ipiece;
	QByteArray qmsg = m_apiece->qsname.toLocal8Bit()  + tr(",").toLocal8Bit() 
		+ QByteArray(tr("%1").arg(m_apiece->totallength).toLocal8Bit() ) + tr(",").toLocal8Bit()  
		+ QByteArray(tr("%1").arg(m_apiece->pieceLength).toLocal8Bit() )+ tr(",").toLocal8Bit()   
        + QByteArray(tr("%1").arg(ipiece).toLocal8Bit() )+ tr(",").toLocal8Bit()
        + QByteArray(stid.toLocal8Bit())+ tr(",").toLocal8Bit()
        + m_pstrdata->mid(icurpos,m_apiece->pieceLength);
	QByteArray tmp  = 'X' + gemfieldCRC(qmsg);//CRC
	qmsg = tmp + qmsg  ;

    QByteArray msg = EnHeadFormat2(qmsg);
	QByteArray data = "DATA " + QByteArray::number(msg.size()) + ' ' ;
	QByteArray dataf =  EnHeadFormat(data)+  msg ;
	return Ewrite(dataf) == dataf.size();
}
bool CxConnection::sendNext(int ipiece)
{ 
	if (ipiece<0)
		return false;
	QString message(tr("%1").arg(ipiece));
	QByteArray msg = message.toUtf8();
	msg = EnHeadFormat(msg);
	QByteArray data = "NEXT " + QByteArray::number(msg.size()) + ' ' ;
	QByteArray dataf =  EnHeadFormat(data) + msg ;
	return (Ewrite(dataf) == dataf.size());
}
bool CxConnection::sendNextResend()
{  
	QString message(tr("resend"));
	QByteArray msg = message.toUtf8();
	msg = EnHeadFormat(msg);
	QByteArray data = "NEXT " + QByteArray::number(msg.size()) + ' ' ;
	QByteArray dataf =  EnHeadFormat(data) + msg ;
	return (Ewrite(dataf) == dataf.size());
}
bool CxConnection::sendData(qint64 iID)
{
    m_icurID = iID;
    m_apiece =&((*m_Pmap)[iID]);

    m_pstrdata = m_apiece->pstringbuf;
	
    if (m_pstrdata->isEmpty())
    {
        m_pdialog->setfinishpiece(m_icurID);
        setdatafree();
        return false;
    }

    m_imaxlen =  m_apiece->totallength/m_apiece->pieceLength
             + (m_apiece->totallength%m_apiece->pieceLength>0?1:0);
	
    m_apiece->m_ipiecesize = m_imaxlen;

	g_section.lock(); 

    qint64 icp = getnextsend();

    if(icp>=0)
    {
        sendOnePiece(icp,m_apiece->qsid);
    }
    g_section.unlock();

    if(icp<0)
    {
        m_pdialog->setfinishpiece(m_icurID);
        setdatafree();
        ShowLog("Data no Piece");
    }

	return true;
}

void CxConnection::timerEvent(QTimerEvent *timerEvent)
{
	if(timerEvent->timerId() == m_dutytimer.timerId())
	{
		m_dutytimer.stop();
		Run();
		m_dutytimer.start(20, this);
	}
    else if(timerEvent->timerId() == CxConnection::getpingtimer().timerId())
	{
        if (CxConnection::getpongtime().elapsed() > PongTimeout)
		{
			ShowLog("no ping DisConnect");
            ioabort();//m_psocket->abort();
			overconnect();

			return;
		}

		QByteArray msg  =  RandSum().toUtf8();
		msg  = EnHeadFormat(msg);
		QByteArray data = "PING " + QByteArray::number(msg.size()) + ' ' ;

		QByteArray dataf =  EnHeadFormatRand(data)+ msg;
		Ewrite(dataf);
	
	} 
}
void CxConnection::processReadyRead()
{
    processRead();
}
void CxConnection::processRead_easy()
{
    QString qstr = CxConnection::getcustomstring();
    if(QString("t1")==qstr.mid(0,2))
    {
        QByteArray data1("g1",2);
        iowrite(data1);
    }
    else if(QString("t2")==qstr.mid(0,2))
    {
        QByteArray data1("g2",2);
        iowrite(data1);
    }


}
void CxConnection::processRead()
{
    if (CxConnection::getstate() == CxConnection::P2Pconnection)
    { //need to change P2P from user List
        QByteArray data = ioread(iobytesAvailable());//m_psocket->read(m_psocket->bytesAvailable());
        if(NULL==m_pattachconnect)
            overconnect();
        else
            m_pattachconnect->iowrite(data);
        return;
    }
    if (CxConnection::getstate() == CxConnection::WaitingForGreeting)
    {
        if (!readProtocolHeader())
        {
            //ShowLog("user custom conneting");
            //overconnect();
            return;
        }
        if (CxConnection::getdatetype() != Greeting)
        {
            ioabort();//m_psocket->abort();
            ShowLog("not valid user connecting");
            overconnect();

            return;
        }

        if (!hasEnoughData())
            return;

        CxConnection::setconnectbuf(Eread(CxConnection::getbytesfordatenum()));
        if (CxConnection::getconnectbuf().size() != CxConnection::getbytesfordatenum())
        {
            return;
        }

        CxConnection::setgreetingusername( getio_peer_address_string() + ':'+ QString::number(iopeerport()));
        CxConnection::ShowLog(tr("Greet:")+CxConnection::getgreetingusername());
        CxConnection::setdatetype(CxConnection::Undefined);
        CxConnection::setbytesfordatenum(0);


        if (!iovalid())//!m_psocket->isValid())
        {
            ShowLog("no valid connect");
            ioabort();//m_psocket->abort();
            return;
        }

        if(0==m_cos)//client
        {
            sendIPKEY();
            if(m_pdialog->getloguse())
            relogin();
        }
        else
        {//server
            ShowLog(tr("User:")+QString(CxConnection::getconnectbuf()));
            SetUser(QString(CxConnection::getconnectbuf()).remove(' '));
        }
        CxConnection::getconnectbuf().clear();
        CxConnection::LoginUSER(this);//set user name in client Greet

        CxConnection::setstate(CxConnection::ReadyForUse);

        emit readyForUse();
    }
    if (CxConnection::getstate() == CxConnection::ReadyForUse)
    {
        do {
            if (CxConnection::getdatetype() == Undefined)
            {
                if (!readProtocolHeader())
                {
                    return;
                }
            }
            if (!hasEnoughData())
                return;
            processData();
        } while (iobytesAvailable());//m_psocket->bytesAvailable() > 0);
    }

}

QString CxConnection::RandSum()
{
	QDateTime now = QDateTime::currentDateTime();
 
	int isec= QTime::currentTime().second();
	
	QString stnowtime = now.toString(QLatin1String("mmssddhhYYYYMM"));
	
	int inum = isec%10;
	
	stnowtime.mid(0,inum);
	
	return stnowtime;//+stnow;
}

int CxConnection::readEnProtolBuffer(int maxSize)
{
	if (maxSize > MaxBufferSize)
		return 0;
    int numBytesBeforeRead = CxConnection::getconnectbuf().size();
    if (numBytesBeforeRead == MaxBufferSize) {
		return 0;
    }
    if (iobytesAvailable() > 0 && CxConnection::getconnectbuf().size() < maxSize)
    {
        CxConnection::setconnectbuf(Eread(16));//fix 16
    }
    QString Qshow = CxConnection::getconnectbuf();
    setcustomstring(Qshow);
	m_pdialog->ClientTextEdit->clear();
	m_pdialog->ClientTextEdit->insertPlainText(m_user +tr(":") +Qshow);
	QStringList	alist  =  Qshow.split(QLatin1String(" "));
	int isize = alist.size();
	if(isize>=2)
	{ 
		ProtocolHeaderbuff = alist.at(0) ;
		ProtocolSizebuff = alist.at(1) ;
	}
	else
	{
		ProtocolHeaderbuff = tr("");
		ProtocolSizebuff = tr("");
	}
    return CxConnection::getconnectbuf().size() - numBytesBeforeRead;
}
int CxConnection::dataLengthForCurrentEnDataType()
{
	int number = ProtocolSizebuff.toInt();
	int numberf = (number/16 + (number%16>0?1:0))*16;
	ProtocolSizebuff.clear();
    CxConnection::getconnectbuf().clear();
	return numberf;
}
bool CxConnection::readProtocolHeader()
{
	int idatalen = readEnProtolBuffer();
    if (idatalen <= 0) 
    {
        return false;
    }

    if (ProtocolHeaderbuff == "PING") {
        CxConnection::setdatetype(CxConnection::Ping);
    } else if (ProtocolHeaderbuff == "PONG") {
        CxConnection::setdatetype(CxConnection::Pong);
	} else if (ProtocolHeaderbuff == "LOGIN") {
        CxConnection::setdatetype(CxConnection::Login);
    } else if (ProtocolHeaderbuff == "MESSAGE") {
        CxConnection::setdatetype(CxConnection::PlainText);
    } else if (ProtocolHeaderbuff == "GREETING") {
        CxConnection::setdatetype(CxConnection::Greeting);
    } else if (ProtocolHeaderbuff == "FINF") {
        CxConnection::setdatetype(CxConnection::GFileINF);
	} else if (ProtocolHeaderbuff == "DATA") {
        CxConnection::setdatetype(CxConnection::CxData);
	} else if (ProtocolHeaderbuff == "NEXT") {
        CxConnection::setdatetype(CxConnection::CxNext);
	}  else if (ProtocolHeaderbuff == "COMM") {
        CxConnection::setdatetype(CxConnection::CxCommand);
	}  else if (ProtocolHeaderbuff == "SAVEF") {
        CxConnection::setdatetype(CxConnection::CxSaveFile);
	}  else if (ProtocolHeaderbuff == "LOGOK") {
        CxConnection::setdatetype(CxConnection::Logok);
	}  
	else
     {
        if(true==getcustomtype())
        {
             processRead_easy();
        }
        else
        {
            if(idatalen<16)
                ShowLog("error package ,next fix here");
            CxConnection::setdatetype(CxConnection::Undefined);
            ioread(idatalen);
            CxConnection::getconnectbuf().clear();
            ProtocolHeaderbuff.clear();
            ShowLog("not valid head");
        }
        return false;
    }
    CxConnection::getconnectbuf().clear();
    ProtocolHeaderbuff.clear();
    CxConnection::setbytesfordatenum(CxConnection::dataLengthForCurrentEnDataType());
    return true;
}

bool CxConnection::hasEnoughData()
{
    //if (transferTimerId) {
    //    QObject::killTimer(transferTimerId);
    //    transferTimerId = 0;
    //}

    if (CxConnection::getbytesfordatenum() <= 0)
        CxConnection::setbytesfordatenum(dataLengthForCurrentEnDataType());

    if (CxConnection::iobytesAvailable()<CxConnection::getbytesfordatenum()
            || CxConnection::getbytesfordatenum() <= 0) {
 //       transferTimerId = startTimer(TransferTimeout);
        return false;
    }

    return true;
}




int CxConnection::IsAdminist(const QString &user)
{
	QString cxname = "cxvision2016";
	QDateTime now = QDateTime::currentDateTime(); 
	QString qmh = now.toString(QLatin1String("MM"));
	QString qdy = now.toString(QLatin1String("dd"));

	QString qadmin =  cxname + qmh + qdy + ipstring;

	QString struser = user; 
	if(struser.remove(tr(" "))==qadmin.remove(tr(" ")))
	{
        ShowLog(tr("sendLogok"));
		m_iuserclass = 1;
		sendLogok(); 
	}
	return 1;
}

void CxConnection::removelnull(QByteArray &buffer0)
{
    int icsize = buffer0.size();
	for(int j=icsize-1;j>=0;j--) 
	{ 
        if(buffer0.at(j)!=' ')
		{
			icsize = j;
			goto NextRunX1;
		}	
	}
NextRunX1:
    buffer0 = buffer0.mid(0,icsize+1);
}
void CxConnection::processData()
{
     CxConnection::setconnectbuf(Eread(CxConnection::getbytesfordatenum()));
    if (CxConnection::getconnectbuf().size() != CxConnection::getbytesfordatenum())
    {
        ShowLog("data loss");
        return;
    }

	QString message;

	int icurnum ;
    switch (CxConnection::getdatetype())
    {
    case Login:
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();

        CxConnection::removelnull(CxConnection::getconnectbuf());
        message = QString::fromUtf8(CxConnection::getconnectbuf()) ;
        CxConnection::setgreetingusername(message.remove(" "));
        IsAdminist(CxConnection::getgreetingusername());

        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();
		break;
    case PlainText:
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();
        message = QString::fromUtf8(CxConnection::getconnectbuf()) ;
        emit newMessage(CxConnection::getgreetingusername(), message);
        if (!(CxConnection::getgreetingusername().isEmpty() || message.isEmpty()))
			ShowLog(tr("MSG:")+message);
        if(message.mid(0,6)=="value_")
         {
            QString qstrname = message.mid(6);
            QStringList	mslist = qstrname.split("_");

            QString varname = mslist[0];
            QString varvalue = mslist[1];
            getdialog()->SetTextEditText(varname);
            getdialog()->SetValueEditText(varvalue);
            getdialog()->SetValue();
        }
        else if(message.mid(0,8)=="compile ")
        {
            QString astr = message.mid(8);
            getdialog()->SetCodeText(astr);
            getdialog()->TestParserX();
        }
        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();
        break;
    case Ping:
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();
		sendPong();

        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();
        break;
    case Pong:
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();
        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();
    
        break;
    case CxCommand:
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();
        CxConnection::removelnull(CxConnection::getconnectbuf());
        message = QString::fromUtf8(CxConnection::getconnectbuf()) ;
		CommandProcess(message);
        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();
		break;
	case CxData:	
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();
        //m_nextdataTime.restart();
        g_datarunsection.lock();
        DataPieceProcess(CxConnection::getconnectbuf());
        setdatafree();
		g_datarunsection.unlock();
        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();
		break;
    case CxNext:
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();
        m_nextdataTime.restart();
        CxConnection::removelnull(CxConnection::getconnectbuf());
        message = QString::fromUtf8(CxConnection::getconnectbuf()) ;
        icurnum = message.toLongLong();
        if (!(CxConnection::getgreetingusername().isEmpty()
		|| message.isEmpty()))
		{
            if(icurnum!=0)
			{
				m_pdialog->updateProgress(tr("Get"),icurnum,m_imaxlen);
			}
		}
		
		if(message.mid(0,6)=="resend")
		{
			ShowLog("Next Resend");
			g_section.lock();  
            qint64 icp = getnextsend();
            if(icp>=0)
            {
                sendOnePiece(icp,m_apiece->qsid);
            }
            g_section.unlock();

            if(icp<0)
            {
                m_pdialog->setfinishpiece(m_icurID);
                setdatafree();
                ShowLog("Data no Piece");
            }
		}
		if(icurnum<m_imaxlen
		&&icurnum>=0)
		{ 
			g_section.lock(); 
			setsendfinish(icurnum);
            qint64 icp = getnextsend();
            if(icp>=0)
            {
                sendOnePiece(icp,m_apiece->qsid);
            }
            g_section.unlock();
            if(icp<0)
            {
                m_pdialog->setfinishpiece(m_icurID);
                setdatafree();
                ShowLog("Data no Piece");
            }
		}
		else
        {
             ShowLog("Next: "+message);

             if(icurnum==99999999||icurnum==90000010)
             {
                  ShowLog("file send finish");
                  m_pdialog->setfinishpiece(m_icurID);
             }
             else if(icurnum==90000000)
             {
                  ShowLog("file part finish");
                  m_pdialog->setfinishpiece(m_icurID);
             }
             else if(icurnum==90000001
                     ||icurnum==90000002)
             {
                  ShowLog("get data reply msg 90000001/2");
                  m_pdialog->setfinishpiece(m_icurID);
             }
             else
             {
                 ShowLog(tr("get data reply msg %1").arg(icurnum));
                 m_pdialog->setfinishpiece(m_icurID);
             }

             m_pdialog->CollectionDataBufClear();
             setdatafree();

        }

        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();

        break;
	case GFileINF:
		//savebuffer.clear();
		break;	
	case CxSaveFile:
		break;
	case Logok:
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();

        CxConnection::LoginOK();

        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();
		break;
    default:
        break;
    }

    CxConnection::setdatetype(CxConnection::Undefined);
    CxConnection::setbytesfordatenum(0);

    CxConnection::getconnectbuf().clear();

}

void CxConnection::CommandProcess(QString &qcomm)
{
	QString qstrdate = qcomm.mid(0,8);
	qcomm = qcomm.mid(8);
	QStringList	alist  =  qcomm.split(QLatin1String(" "));
	QString QScom;
	QString QSparm;
	QString QSparmall = qcomm;
	//////////////////////////////////////////////////////////////////////////
	for(int i = 0;i<qcomm.size() ;i++)
	{
		QChar achar = qcomm.at(i);
		if(achar==' ')
		{
			QScom = qcomm.mid(0,i);
			QSparm = qcomm.mid(i+1);
			goto CPNEXT0;
		}
	}
CPNEXT0:
	if(QScom=="")
	{
		QScom = qcomm;
	}
	//////////////////////////////////////////////////////////////////////////

	QString QSparm1;
	QString QSparm2;
	QString QSparm3;
	QString QSparm4;
	QString QSparm5;
	QString QSparm6;
	int isize = 0;
	//int ifusize =alist.size(); 
	//if(ifusize>=2)
	{ 
	//	QScom = alist.at(0) ;
	//	QSparm = alist.at(1) ; 
		QStringList	alistparm  = QSparm.split(QLatin1String(","));	
		isize = alistparm.size(); 
		if(isize>=2)
		{ 
			QSparm1 = alistparm.at(0) ;
			QSparm2 = alistparm.at(1) ;
			if(isize>=3)
			{
				QSparm3 = alistparm.at(2) ;
				if(isize>=4)
				{
					QSparm4 = alistparm.at(3) ;
					if(isize>=5)
					{
						QSparm5 = alistparm.at(4) ; 
					} 
				} 
			}
		}
		else
		{
			QSparm1 = QSparm;
		}
	}
	ShowLog(tr("TIME:")+qstrdate +tr(" ") +qcomm);
	if(QScom=="rekey")
	{
		m_dutytimer.stop();
        //pingTimer.stop();
        //pongTime.restart();
		QDateTime now = QDateTime::currentDateTime();
		QString qyear = now.toString(QLatin1String("yyyy"));
		QString qmh = now.toString(QLatin1String("MM"));
		QString qdy = now.toString(QLatin1String("dd"));
		int iy = qyear.toInt();
		int im = qmh.toInt();
		int id = qdy.toInt();

		//ipstring = QSparm1+QSparm2+QSparm3+QSparm4+QSparm5;
		ipstring = QSparm1+QSparm3+QSparm4;
				  //ip4,iport,ip_1,ip_4,iport2
		int ip1 =  QSparm1.toInt();
		int ip2 =  QSparm2.toInt();//
		int ip3 =  QSparm3.toInt();
		int ip4 =  QSparm4.toInt();
		int iport =  QSparm5.toInt(); 

		SetKey(ip4,id,iport,ip4,
			id,im,iport,ip4,
			iport,id,iport,ip4,
			ip4,id,iport,ip4);
		
		ipstring = "U" + ipstring +"000000000";
		
		QString qstrtime = QTime::currentTime().toString("Chhmmsszzz");
		
		ipstring =  ipstring.mid(0,10)	+ qstrtime;	//("Uhhmmsszzz");//U123359375C123415656
 
		SetUser(ipstring);//reset user
		
		m_pdialog->ReFlashUSER(); 

        //pingTimer.start(PingInterval,this);
        //pongTime.start();
		m_dutytimer.start(20, this);
		sendMessage("[peer REK OK]");
		ShowLog(tr("[Local REK ok]"));
		

		//m_isendfinish_duty = 1;	
		//m_iuserclass = 1;
		return;
	}
	if(QScom=="setkey")
	{
		QDateTime now = QDateTime::currentDateTime();
		QString qyear = now.toString(QLatin1String("yyyy"));
		QString qmh = now.toString(QLatin1String("MM"));
		QString qdy = now.toString(QLatin1String("dd"));
		int iy = qyear.toInt();
		int im = qmh.toInt();
		int id = qdy.toInt();

		ipstring = QSparm1+QSparm2+QSparm3+QSparm4+QSparm5;

		int ip1 =  QSparm1.toInt();
		int ip2 =  QSparm2.toInt();
		int ip3 =  QSparm3.toInt();
		int ip4 =  QSparm4.toInt();
		int iport =  QSparm5.toInt(); 

		SetKey(ip4,id,iport,ip4,
			id,im,iport,ip4,
			iport,id,iport,ip4,
			ip4,id,iport,ip4);

        //pingTimer.start(PingInterval,this);
        //pongTime.start();
		sendMessage("[connect Valid]");
		ShowLog(tr("[connect ok]"));
		//m_pdialog->AddConnections(this);
		return;
	}
	if(QScom=="sendfinish")
	{
		SendFinish(QSparm1,QSparm2,qstrdate);
		return;
	}
	if(QScom=="ircmsg")
	{
		m_pdialog->IrcMsg(this,qcomm);
		return;
	}
#ifdef CXVISIONBSERVER 

	//if(1==m_iuserclass)
#endif
	{
		{		
			AddDuty_frontstr("sendfinish Duty,"+QScom,qstrdate,3,QScom,QSparm1,QSparm2,QSparm3,QSparmall);
		
			m_qsprecommand = qcomm;
		}
		
	}
#ifdef CXVISIONBSERVER 
	//else
	//{
	//	sendMessage("[NO LOGIN!]");
	//}
#endif
}
void CxConnection::DataPieceProcess(QByteArray &qcomm)
{
	//QSparm0 = alist.at(0) ;//qsname
	//QSparm1 = alist.at(1) ;//totallength
	//QSparm2 = alist.at(2) ;//pieceLength
	//QSparm3 = alist.at(3) ;//icurpiece
	//QSparm4 = alist.at(4) ;//content
    QByteArray QSparm[6];

	int ibegin = 0;
	int iend = 0;
	int iqnum = 0;
	int inulnum = 0;
    int isize = qcomm.size();
	for(int i = 0;i<isize ;i++)
	{
		QChar achar = qcomm.at(i);
		if(achar!=' ')
		{
			inulnum = i;
			goto NEXTRUN0;
		}
	}
NEXTRUN0:	
	ibegin = inulnum + 1;//'X'
//CRC
    
	QByteArray tmpget;
	tmpget[0] = qcomm.at(ibegin);
    tmpget[1] = qcomm.at(ibegin+1);
    QByteArray tmp  = gemfieldCRC(qcomm.mid(ibegin+2));//CRC[0]+ CRC[1]

	if(tmpget[0]!=tmp[0]
    ||tmpget[1]!=tmp[1] )
	{
		ShowLog(tr("CRC Error Get:")+tmpget.toHex() + tr("I:")+tmp.toHex())  ; 
	 	sendNextResend();	
	 	return;
	}
	
    ibegin = inulnum+3; //'X'+CRC[0]+ CRC[1]+CRC[2]+ CRC[3]
//
    for(int i = inulnum+3;i<isize ;i++)
	{
		QChar achar = qcomm.at(i);
		if(achar==',')
		{
            QSparm[iqnum] = qcomm.mid(ibegin,i-ibegin);
			iqnum = iqnum +1;
			ibegin = i+1;
			if(iqnum>=5)
				goto NEXTRUN1;
		}
	}

NEXTRUN1:
	QSparm[5] = qcomm.mid(ibegin);
	//show 
	//////////////////////////////////////////////////////////////////////////
	m_pdialog->ClientTextEdit->clear();
	//////////////////////////////////////////////////////////////////////////
    int itolsize =QSparm[1].toInt();
    int ipsize = QSparm[2].toInt();
    int icp = QSparm[3].toInt();
 
	//ShowLog(tr("CRC :")+tmp.toHex() +tr(" num: %1 %2 %3").arg(itolsize).arg(ipsize).arg(icp));
	
	g_filesection.lock();

    if(ipsize>0)
        m_imaxlen = (itolsize/ipsize) + ((itolsize%ipsize)>0?1:0);
    else
        m_imaxlen = 1;
    int igetnum = m_pdialog->getonepiecefilex(icp,ipsize,itolsize, QSparm[0],QSparm[4],QSparm[5]);
 
    //int igetnum = m_pdialog->getfinishnum(m_imaxlen);

    g_filesection.unlock();
    if(igetnum!=1)
	{
        if (!(CxConnection::getgreetingusername().isEmpty() ))
		{
			m_pdialog->updateProgress(tr("Get"),igetnum,m_imaxlen);
		}
	} 
	if(igetnum<m_imaxlen)
		sendNext(icp);//finish this piece
	else
    {
        sendNext(igetnum);
        return;


        ///old ver
        int ineedsendendsign = 1;
        //if(2!=m_pdialog->getfilefinish())
        //{
        //    ShowLog(QString(QSparm[4]) +tr("[Data End 0]"));
        //	m_pdialog->settransferover();
        //}
       // else
       // {
       //     sendNext(90000000);
       //     ShowLog(QString(QSparm[4]) +tr("[Data End 1]"));
       //     return;// connect resend data filter
       // }
		g_datafinishsection.lock();

		QByteArray igettype;
		QByteArray igetstring;
		for(int i = 0;i<QSparm[0].size() ;i++)
		{
			QChar achar = QSparm[0].at(i);
			if(achar=='_')
			{
				igettype = QSparm[0].mid(0,i);
				igetstring = QSparm[0].mid(i+1);
				goto NEXTRUN2;
			}
		}
NEXTRUN2:
		if(igettype=="file")
		{
///			m_pdialog->Get_SaveFileSend(igetstring);
		}
        else if(igettype=="Tfile")
        {
           int iends = 0;
           if(0==iends)
               ineedsendendsign = 1;
            else if(1==iends)
               ineedsendendsign = 2;
           else if(2==iends)
               ineedsendendsign = 3;
           else
               ineedsendendsign = 4;
        }
        else if(igettype=="Ctl")
        {
            m_pdialog->Get_ControlString(igetstring);
        }
		else if(igettype=="datefile")
		{
            QString strdate = QString(QSparm[4].toStdString().c_str());
            m_pdialog->ResetDateLoop(strdate,1);
            m_pdialog->SetSQLRecord(strdate);//
            ShowLog(tr("[datafile Finish]"));
			m_pdialog->Get_SaveDateFileSend(igetstring);
		}
		else if(igettype=="page")
		{
			m_pdialog->Get_ShowPageSend();
		}
		else if(igettype=="image")
		{
			QByteArray qbw;
			QByteArray qbh;
			QByteArray qbtype;
			int i_num = 0;
			int iprenum = 0;
			for(int i = 0;i<igetstring.size() ;i++)
			{
				QChar achar = igetstring.at(i);
				if(achar=='_')
				{
					if(0==i_num)
					{
						qbw = igetstring.mid(iprenum,i-iprenum);
						iprenum = i + 1;
						i_num = i_num + 1;
					}
					else if(1==i_num)
					{
						qbh = igetstring.mid(iprenum,i-iprenum);
						iprenum = i + 1;
						i_num = i_num + 1;
						goto NEXTRUN3;
						 
					}

				}
			}
			if(i_num<=1)
				qbh = igetstring.mid(iprenum);
NEXTRUN3:
			int iw =qbw.toInt();
			int ih =qbh.toInt();
//			m_pdialog->Get_SaveImageSend(iw,ih);
		}
		else if(igettype=="imageframe")//image frame stream
		{
			QByteArray qbw;
			QByteArray qbh;
			QByteArray qbtype;
			int i_num = 0;
			int iprenum = 0;
			for(int i = 0;i<igetstring.size() ;i++)
			{
				QChar achar = igetstring.at(i);
				if(achar=='_')
				{
					if(0==i_num)
					{
						qbw = igetstring.mid(iprenum,i-iprenum);
						iprenum = i + 1;
						i_num = i_num + 1;
					}
					else if(1==i_num)
					{
						qbh = igetstring.mid(iprenum,i-iprenum);
						iprenum = i + 1;
						i_num = i_num + 1;
						goto NEXTRUN4;

					}

				}
			}
			if(i_num<=1)
				qbh = igetstring.mid(iprenum);
NEXTRUN4:
			int iw =qbw.toInt();
			int ih =qbh.toInt();
		//	ShowLog(igetstring + tr("GetImage->%1 _ %2").arg(iw).arg(ih));
        //	m_pdialog->Get_SaveImageFrameSend(iw,ih,igetstring);
		}
		else if(igettype=="list")
		{
			 m_pdialog->Get_SaveListSend();
		}
		else if(igettype=="sql")
		{
             m_pdialog->Get_SqlSend(this);
		}
		else if(igettype=="sqlx")
		{
			//
			//resetflag

			m_pdialog->Get_SqlxSend(this);
            QString strdate = QSparm[4].toStdString().c_str();
            m_pdialog->ResetDateLoop(strdate,1);
			 
            //g_dutyfinishsection.lock();
            setdutyfree();
            //g_dutyfinishsection.unlock();

            ShowLog(tr("[SqlFinish]"));
			if(m_dutylist.size()>0)
			{	
				m_dutylist.pop_front();
				m_pdialog->removelist(0);
				if(m_dutylist.size()==0)
					m_pdialog->clearlist();
			}
		}
		else if(igettype=="sqlf")
		{
            //
			m_pdialog->Get_SaveDateFileSend(igetstring);

            QString strdate = QSparm[4].toStdString().c_str();
            m_pdialog->ResetDateLoop(strdate,1);

            //g_dutyfinishsection.lock();
            setdutyfree();
            //g_dutyfinishsection.unlock();

            ShowLog(tr("[Sqlf Finish]"));
			if(m_dutylist.size()>0)
			{	
				m_dutylist.pop_front();
				m_pdialog->removelist(0);
				if(m_dutylist.size()==0)
					m_pdialog->clearlist();
			}
		}
		else
		{
//			m_pdialog->Get_SaveFileSend(igetstring);
		}
		
		m_pdialog->RemoveRecoT(QString(QSparm[4]));
		g_datafinishsection.unlock();
        if(1==ineedsendendsign)
            sendNext(99999999);
        else if(2==ineedsendendsign)
            sendNext(90000000);
        else if(3==ineedsendendsign)
            sendNext(90000001);
        else if(4==ineedsendendsign)
            sendNext(90000002);

		//Clear();
		//////////////////////////////////////////////////////////////////////////
	}

	//////////////////////////////////////////////////////////////////////////

} 
bool CxConnection::WaitNextMsg(int iwaittime)
{
	if (m_nextdataTime.elapsed() > iwaittime)//5*1000) 
    {
		return true;
	}
	return false;
}
QByteArray CxConnection::Test(QByteArray data)
{  
	int isize = data.size();

	//memcpy(pchar,data.data(),isize);
	//int iesize =	Encrypt(pchar,isize);
	//Decrypt(pchar,iesize);

//	QByteArray data1(pchar,iesize);

//	return data1;
return data;
}
void CxConnection::ShowLog(const QString &strlog)
{
	m_pdialog->ShowLog(this,strlog);
}
void CxConnection::AddLog(const QString &strlog)
{
   // m_pdialog->AddLog(strlog);
}
void CxConnection::SetLog(const QString &strlog)
{
   // m_pdialog->SetLog(strlog);
}
QByteArray CxConnection::getbufx() const
{ 
	return  m_databufx;
}
QByteArray *CxConnection::getbufp()
{ 
	return  &m_databufx;
}

bool CxConnection::getloguse()
{
    return m_pdialog->getloguse();
}
void CxConnection::LoginUSER(CxConnection*pconnect)
{
    m_pdialog->LoginUSER(pconnect);
}
void CxConnection::LoginOK()
{
    m_pdialog->LoginOK();
}
void CxConnection::setbufx(const QByteArray &bufx )
{ 
    m_databufx = bufx;
}
void CxConnection::SendFinish(const QString &qmsg1,const QString &qmsg2,const QString &qstrdate)
{

	if(qmsg1==tr("Duty"))
	{	

        //g_dutyfinishsection.lock();
        setdutyfree();
        //g_dutyfinishsection.unlock();
 
        ShowLog(tr("[DutyFinish:")+qmsg2+tr("]"));
		int idutyid = qmsg2.toInt();
		int idutysize = m_dutylist.size();

		
		int inum = 0;
		if(idutysize>0)
		{	
			m_dutylist.pop_front();
			m_pdialog->removelist(0);
			if(m_dutylist.size()==0)
				m_pdialog->clearlist();
 
		}
	} 


}
void CxConnection::Clear()
{
    setdatafree();
    setdutyfree();
    m_dutylist.clear();

    ShowLog("clear reset connection");
}
void CxConnection::Reset()
{
    setdatafree();
    setdutyfree();
    ShowLog("reset connection");
}
void CxConnection::AddDuty(const cxduty &aduty)
{
	m_dutylist.push_back(aduty);
}
void CxConnection::AddDuty(const QString &qstring,const QString &qstime,int itype)
{
    QString aqstime;
	if(qstime==tr("0")||qstime==tr(""))
        aqstime = tr("%1").arg(m_sendTime.elapsed());
	else 
		aqstime = qstime;

	cxduty aduty;
	aduty.m_istats = 0;
	aduty.m_itype = itype;
    aduty.m_stime = aqstime;
	aduty.m_stcomm = qstring;

	m_dutylist.push_back(aduty);
		
	m_pdialog->AddSendReco(this,aduty.m_stime,qstring);
 
}
void CxConnection::AddDuty_frontstr(const QString &qstring,const QString &qstime,int itype,const QString &qsname ,const QString &qsparm1,const QString &qsparm2,const QString &qsparm3,const QString &qsparmall)
{
    //int its = 	QTime::currentTime().second();
    //int itm = 	QTime::currentTime().minute();
    //int ith = 	QTime::currentTime().hour();

    //QString qsdd = QDateTime::currentDateTime().toString(QLatin1String("dd"));
    //int itd = qsdd.toInt();
    //int inum = itd *1000000 +ith* 10000 + itm *100 + its;
    //qsdd =  qsdd + QTime::currentTime().toString(QLatin1String("hhmmss"));

	QString aqstime;
	if(qstime==tr("0")||qstime==tr(""))
        aqstime =  tr("%1").arg(Dialog::GetGolbalTime());
	else 
		aqstime = qstime;

	cxduty aduty;
	aduty.m_stname = qsname;
	aduty.m_stparm1 = qsparm1;
	aduty.m_stparm2 = qsparm2;
	aduty.m_stparm3 = qsparm3;
	aduty.m_istats = 0;
	aduty.m_itype = itype;
	aduty.m_stime = aqstime;
	aduty.m_stcomm = qstring;
	aduty.m_qsparmall = qsparmall;

	m_dutylist.push_front(aduty);

	//m_pdialog->widgetList->insertItem(0,tr("[%1 TYPE(%2)]:").arg(aduty.m_stime).arg(aduty.m_itype)+aduty.m_stcomm);

	m_pdialog->AddSendReco(this,aduty.m_stime,qstring);
}
void CxConnection::AddDuty_front(const cxduty &aduty)
{
	m_dutylist.push_front(aduty);
}
void CxConnection::AddMsg(const QString &qstring)
{ 
	m_msglist.push_back(qstring);
}
bool CxConnection::IsBusy()
{
    if(iovalid())//m_psocket->isValid())
	{
		if(1==m_isendfinish_data
			&&1==m_isendfinish_duty)
			return false;
	}
 
	return true;
}
void CxConnection::Run()
{
    if(iovalid())
	{
		if(1==m_isendfinish_data
         &&1==m_isendfinish_duty)
        {
            Send_Data();
            Duty_Run();
		}
		else if(0==m_isendfinish_data
			&&1==m_isendfinish_duty)
        {
            if( WaitNextMsg())
            {
                ShowLog("Wait Data Over Time reset connection");
                setdatafree();
                return;
            }
		}
		else if(1==m_isendfinish_data
			&&0==m_isendfinish_duty)
		{
			int idatasize = m_dutylist.size();
			if(idatasize>0)
			{ 
					if(WaitNextMsg())
					{ 
                        ShowLog("Wait Duty Over Time new connect");
                        //g_dutyfinishsection.lock();
                        setdutyfree();
                        //g_dutyfinishsection.unlock();

                        setdatafree();
						return;
					} 
			}
        }
		if(1==m_isendfinish_data)
		{
			int imsgsize = m_msglist.size();
			if(imsgsize>0)
			{ 
				sendMessage(m_msglist[0]);
				m_msglist.pop_front();
			} 
		}
	}
}




void CxConnection::Send_Data()
{
	qint64 iID = m_pdialog->getsendpiece();
	if(iID>=0)
	{
		setdatabusy();
		m_pdialog->setsendpiece(iID);
		sendData(iID);
	}
}
void CxConnection::Duty_Run()
{
    int idutysize = m_dutylist.size();
    if(idutysize>0)
    {
        switch(m_dutylist[0].m_itype)
        {
                case 0:
                {
                        qint64 inum = Dialog::GetGolbalTime();
                        QString qsdd = tr("00000000").arg(inum);
                        qsdd = qsdd.mid(0,8);
                        if(inum>m_dutylist[0].m_stime.toLongLong()
                            &&1!=m_dutylist[0].m_istats)
                        {
                            m_dutylist[0].m_istats = 1;
                            setdutybusy();
                            if(m_dutylist[0].m_stcomm.mid(0,9)==tr("listclear"))
                            {
                                m_pdialog->Run_Clear();
                                if(m_dutylist.size()>0)
                                {
                                    m_dutylist.pop_front();
                                    m_pdialog->removelist(0);
                                    if(m_dutylist.size()==0)
                                        m_pdialog->clearlist();
                                }
                            }
                            else if(m_dutylist[0].m_stcomm.mid(0,10)==tr("pageclass "))
                            {
                                QStringList alist = m_dutylist[0].m_stcomm.mid(10).split(",");
                                if(alist.size()>1)
                                {
                                    QString qsp1,qsp2,qsp3,qsp4;
                                    if(alist.size()>0)
                                        qsp1 =alist[0];
                                    if(alist.size()>1)
                                        qsp2 =alist[1];
                                    if(alist.size()>2)
                                        qsp3 =alist[2];
                                    if(alist.size()>3)
                                        qsp4 =alist[3];
                                    m_pdialog->Run_PageElementClassic(qsp1,qsp2,qsp3,qsp4);

                                    if(m_dutylist.size()>0)
                                    {
                                        m_dutylist.pop_front();
                                        m_pdialog->removelist(0);
                                        if(m_dutylist.size()==0)
                                            m_pdialog->clearlist();
                                    }
                                }
                            }
                            else if(m_dutylist[0].m_stcomm.mid(0,11)==tr("newconnect "))
                                    {
                                        QStringList alist = m_dutylist[0].m_stcomm.split(" ");
                                        if(alist.size()>=2)
                                        {
                                            m_dutylist[0].m_stparm1 = alist[1];
                                            m_pdialog->new_connect(this,m_dutylist[0].m_stparm1);//username
                                        }
                                        else
                                            m_pdialog->new_connect(this,tr("1"));//username
                                        m_dutylist.pop_front();
                                        m_pdialog->removelist(0);
                                        if(m_dutylist.size()==0)
                                            m_pdialog->clearlist();
                                        setdutyfree();
                                    }
                            else
                                    {
                                        if(m_dutylist[0].m_stime.toLongLong()!=0)
                                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                                        else
                                            sendCommand(m_dutylist[0].m_stcomm,qsdd);
                                    }

                            setdatafree();
                            m_pdialog->setWindowTitle(QString::fromLatin1("CxVisionAImini V5.8 T:") + qsdd);
                        }
                        else if(inum>m_dutylist[0].m_stime.toLongLong()
                            &&1==m_dutylist[0].m_istats)
                        {
                            if(WaitNextMsg())
                            {
                                setdutyfree();
                                m_dutylist.pop_front();
                                m_pdialog->removelist(0);
                                if(m_dutylist.size()==0)
                                    m_pdialog->clearlist();
                                setdatafree();//m_nextdataTime.restart();
                                m_pdialog->setWindowTitle(QString::fromLatin1("CxVisionAImini V5.8 T:") + qsdd);
                                return;
                            }
                        }
                }
                    break;
                case 5:
                    {
                        if( 1!=m_dutylist[0].m_istats)
                        {
                            m_dutylist[0].m_istats = 1;
                            //g_dutyfinishsection.lock();
                            setdutybusy();
                            //g_dutyfinishsection.unlock();
                            {
                                if(m_dutylist[0].m_stcomm.mid(0,9)==tr("listclear"))
                                {
                                    m_pdialog->Run_Clear();

                                    if(m_dutylist.size()>0)
                                    {
                                        m_dutylist.pop_front();
                                        m_pdialog->removelist(0);
                                        if(m_dutylist.size()==0)
                                            m_pdialog->clearlist();
                                    }
                                }
                                else if(m_dutylist[0].m_stcomm.mid(0,10)==tr("pageclass "))
                                {
                                    QStringList alist = m_dutylist[0].m_stcomm.mid(10).split(",");
                                    if(alist.size()>1)
                                    {
                                        QString qsp1,qsp2,qsp3,qsp4;
                                        if(alist.size()>0)
                                            qsp1 =alist[0];
                                        if(alist.size()>1)
                                            qsp2 =alist[1];
                                        if(alist.size()>2)
                                            qsp3 =alist[2];
                                        if(alist.size()>3)
                                            qsp4 =alist[3];

                                        m_pdialog->Run_PageElementClassic(qsp1,qsp2,qsp3,qsp4);

                                        if(m_dutylist.size()>0)
                                        {
                                            m_dutylist.pop_front();
                                            m_pdialog->removelist(0);
                                            if(m_dutylist.size()==0)
                                                m_pdialog->clearlist();
                                        }
                                    }
                                }
                                else if(m_dutylist[0].m_stcomm.mid(0,11)==tr("newconnect "))
                                {
                                    QStringList alist = m_dutylist[0].m_stcomm.split(" ");
                                    if(alist.size()>=2)
                                    {
                                        m_dutylist[0].m_stparm1 = alist[1];
                                        m_pdialog->new_connect(this,m_dutylist[0].m_stparm1);//username
                                    }
                                    else
                                        m_pdialog->new_connect(this,tr("1"));//username
                                    m_dutylist.pop_front();
                                    m_pdialog->removelist(0);
                                    if(m_dutylist.size()==0)
                                        m_pdialog->clearlist();
                                    setdutyfree();
                                }
                                else
                                {
                                     sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);

                                }

                            }
                            setdatafree();
                            //m_nextdataTime.restart();
                        }
                        else if( 1==m_dutylist[0].m_istats)
                        {
                            if(WaitNextMsg())
                            {
                                //g_dutyfinishsection.lock();
                                setdutyfree();
                                //g_dutyfinishsection.unlock();

                                m_dutylist.pop_front();
                                m_pdialog->removelist(0);
                                if(m_dutylist.size()==0)
                                    m_pdialog->clearlist();
                                setdatafree();
                                return;
                            }
                        }
                    }
                    break;
                case 2://finish signal
                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                    if(m_dutylist.size()>0)
                    {
                        m_dutylist.pop_front();
                        m_pdialog->removelist(0);
                        if(m_dutylist.size()==0)
                            m_pdialog->clearlist();
                    }
                    break;
                case 3://finish signal
                    {
                        if(m_dutylist[0].m_stname=="wget")
                        {
                            sendMessage("wget:"+m_dutylist[0].m_stparm1);
                            m_pdialog->WGetPage(this,m_dutylist[0].m_stparm1,m_dutylist[0].m_stime);
                        }
                        else if(m_dutylist[0].m_stname=="cxpy")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->RunPyton(m_dutylist[0].m_qsparmall.mid(5));
                            sendMessage("cxpy:"+m_dutylist[0].m_qsparmall.mid(5));
                        }
                        else if(m_dutylist[0].m_stname=="wsql")
                        {
                            sendMessage("wsql:"+m_dutylist[0].m_stparm1);
                            m_pdialog->WSQLPage(this,m_dutylist[0].m_stparm1,m_dutylist[0].m_stime);
                        }
                        else if(m_dutylist[0].m_stname=="wsqlc")
                        {
                            sendMessage("wsqlc:"+m_dutylist[0].m_stparm1);
                            m_pdialog->WSQLPageC(this,m_dutylist[0].m_stparm1,m_dutylist[0].m_stime);
                        }
                        else if(m_dutylist[0].m_stname=="wfile")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->WGetFile(this,m_dutylist[0].m_stparm1,m_dutylist[0].m_stime);
                        }
                        else if(m_dutylist[0].m_stname=="fsql")
                        {
                            sendMessage("fsql:"+m_dutylist[0].m_stparm1);
                            m_pdialog->WSQLGetFile(this,m_dutylist[0].m_stparm1,m_dutylist[0].m_stime);
                        }
                        else if(m_dutylist[0].m_stname=="getpage")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->Send_Page_Multi(m_user,0,m_dutylist[0].m_stime);
                        }
                        else if(m_dutylist[0].m_stname=="getpic")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->Send_Picture_Multi(m_user,0,m_dutylist[0].m_stime);
                        }
                        else if(m_dutylist[0].m_stname=="getfile")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->SendLocalFile_Multi(m_user,m_dutylist[0].m_stparm1,m_dutylist[0].m_stime);
                        }
                        else if(m_dutylist[0].m_stname=="getdesktop")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->Send_Desktop_Multi( m_user,m_dutylist[0].m_stparm1,m_dutylist[0].m_stime);
                        }
                        else if(m_dutylist[0].m_stname=="getview")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->Send_View_Multi(m_user,m_dutylist[0].m_stparm1,m_dutylist[0].m_stime);
                        }
                        else if(m_dutylist[0].m_stname=="setview")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->Set_FrameView(m_dutylist[0].m_stparm1.toInt(),m_dutylist[0].m_stparm2.toInt(),m_dutylist[0].m_stparm3.toInt());
                        }
                        else if(m_dutylist[0].m_stname=="getmsg")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->Send_MouseKeyBoardMsg_Multi(m_dutylist[0].m_stparm1,m_dutylist[0].m_stime);
                        }
                        else if(m_dutylist[0].m_stname=="getlist")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);

                            if(m_dutylist[0].m_stparm2!=""
                            ||m_dutylist[0].m_stparm2!=" ")
                                m_pdialog->Send_PageList_Multi(m_user,m_dutylist[0].m_stparm1.toInt(),m_dutylist[0].m_stparm2,0,m_dutylist[0].m_stime);
                            else
                                m_pdialog->Send_PageList_Multi(m_user);
                        }
                        else if(m_dutylist[0].m_stname=="getsql")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);

                            if(m_dutylist[0].m_stparm2!=""
                                ||m_dutylist[0].m_stparm2!=" ")
                                m_pdialog->Send_PageSQL_Multi(m_user,m_dutylist[0].m_stparm1.toInt(),m_dutylist[0].m_stparm2,0,m_dutylist[0].m_stime);
                            else
                                m_pdialog->Send_PageSQL_Multi(m_user,1,"",0,m_dutylist[0].m_stime);
                        }
                        else if(m_dutylist[0].m_stname=="dir")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->FileDir(this,m_dutylist[0].m_stparm1);
                        }
                        else if(m_dutylist[0].m_stname=="irc")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->IrcOpt(this,m_dutylist[0].m_stparm1.toInt(),m_dutylist[0].m_stparm2,m_dutylist[0].m_stparm3);
                        }
                        else if(m_dutylist[0].m_stname=="psize")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            setpiecesize(m_dutylist[0].m_stparm1.toInt());
                        }
                        else if(m_dutylist[0].m_stname=="search")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->GSearch(this,m_dutylist[0].m_stparm1.toInt(),m_dutylist[0].m_stparm2);
                        }
                        else if(m_dutylist[0].m_stname=="req")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->setrequeststring(m_dutylist[0].m_stparm1.toInt());
                        }
                        else if(m_dutylist[0].m_stname=="clear")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->Set_Clear(this);
                        }
                        else if(m_dutylist[0].m_stname=="iplist")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->Send_ConnectList(this);
                        }
                        else if(m_dutylist[0].m_stname=="userlist")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->Send_UserList(this);
                        }
                        else if(m_dutylist[0].m_stname=="all")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->AllShow(this);
                        }
                        else if(m_dutylist[0].m_stname=="ver")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            AddMsg("Ver171106");
                        }
                        else if(m_dutylist[0].m_stname=="p2p")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->P2P_connect(this,m_dutylist[0].m_stparm1);
                        }
                        else if(m_dutylist[0].m_stname=="u2u")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->U2U_connect(this,m_dutylist[0].m_stparm1,m_dutylist[0].m_stparm2);

                        }
                        else if(m_dutylist[0].m_stname=="reset")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->reset_connect(this,m_dutylist[0].m_stparm1);
                        }
                        else if(m_dutylist[0].m_stname=="resetall")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->reset_all();
                        }
                        else if(m_dutylist[0].m_stname=="new")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->new_connect(this,m_dutylist[0].m_stparm1);//username
                        }
                        else if(m_dutylist[0].m_stname=="mk")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->MKDir(m_dutylist[0].m_stparm1);
                        }
                        else if(m_dutylist[0].m_stname=="rm")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->RMDir(m_dutylist[0].m_stparm1);
                        }
                        else if(m_dutylist[0].m_stname=="filecopy")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->cxCopyFile(m_dutylist[0].m_stparm1,m_dutylist[0].m_stparm2);
                        }
                        else if(m_dutylist[0].m_stname=="filerename")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->RenameFile(m_dutylist[0].m_stparm1,m_dutylist[0].m_stparm2);
                        }
                        else if(m_dutylist[0].m_stname=="fileremove")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->RemoveFile(m_dutylist[0].m_stparm1);
                        }
                        else if(m_dutylist[0].m_stname=="EXE")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->runWithQtInEnvironment(m_dutylist[0].m_stparm1);
                        }
                        else if(m_dutylist[0].m_stname=="update")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->UpDatePro();
                        }
                        else if(m_dutylist[0].m_stname=="reboot")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->ResetPro();
                        }
                        else if(m_dutylist[0].m_stname==">>")
                        {
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            m_pdialog->setEditText(m_dutylist[0].m_qsparmall.mid(3));
                            //m_pdialog->sendCommand();

                            sendMessage("run>>"+m_dutylist[0].m_qsparmall.mid(5));
                        }
                        else
                        {//unknow comm
                            sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                        }
                        if(m_dutylist.size()>0)
                        {
                            m_dutylist.pop_front();
                            m_pdialog->removelist(0);
                            if(m_dutylist.size()==0)
                                m_pdialog->clearlist();
                        }
                    }
                    break;
                case 4://loacla signal
                    break;
        }
        return;
    }

}
void CxConnection::setpiecesize(int isize)
{
	m_pdialog->SetPieceSize(isize);
}
///
QString CxConnection::getio_local_address_string()
{
  return  m_psocket->localAddress().toString();
}
QString CxConnection::getio_peer_address_string()
{
    return  m_psocket->peerAddress().toString();
}
bool CxConnection::iovalid()
{
    if(m_psocket!=NULL)
        return m_psocket->isValid();
    else
        return false;
}
void CxConnection::ioclose()
{
    if(m_psocket!=NULL)
        m_psocket->close();
}
qint64  CxConnection::iowrite(const QByteArray &data)
{
    return m_psocket->write(data);
}
QByteArray  CxConnection::ioread(qint64 maxlen)
{
    return m_psocket->read(maxlen);
}
QByteArray  CxConnection::ioreadall()
{
    return m_psocket->readAll();
}

int  CxConnection::iolocalport()
{
    return m_psocket->localPort();
}
int  CxConnection::iopeerport()
{
    return m_psocket->peerPort();
}
void  CxConnection::ioabort()
{
    if(m_psocket!=NULL)
        m_psocket->abort();
}
qint64 CxConnection::iobytesAvailable()
{
    return m_psocket->bytesAvailable();
}
void CxConnection::connectToHost(QHostAddress adress,int iport)
{
    m_psocket->connectToHost(adress,iport);
}
